This example shows how to get the size of the LinkedList (length of LinkedList) object in Java. The example also shows how to iterate the LinkedList using the size method and a for loop.
How to get the size of the LinkedList in Java (length of the LinedList)?
The size
method of the LinkedList class returns the number of elements contained in the LinkedList object.
1 |
public int size() |
The size
method returns an int value which is equal to the number of elements contained in the LinkedList object.
When you initially create an empty LinkedList object, the size
method returns 0 as there are no elements in the LinkedList. As and when you add or remove elements from the LinkList object, the size keeps on changing according to the change we made to the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.LinkedList; public class LinkedListSizeExample { public static void main(String[] args) { //create new LinkedList object LinkedList<String> linkedListColors = new LinkedList<String>(); /* * To get the size of the LinkedList, use the * size method */ //it should return 0 as there are no elements in the list System.out.println( linkedListColors.size() ); //add an element linkedListColors.add("Green"); //it should return 1 as there is one element in the list System.out.println( linkedListColors.size() ); } } |
Output
1 2 |
0 1 |
How to use the size to iterate the LinkedList using for loop?
You can use the size of the LinkedList returned by the size
method to iterate over LinkedList elements using the for loop as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.LinkedList; public class LinkedListSizeExample { public static void main(String[] args) { //create new LinkedList object LinkedList<String> linkedListColors = new LinkedList<String>(); //add elements linkedListColors.add("Red"); linkedListColors.add("Green"); linkedListColors.add("Blue"); //iterate over elements using the LinkedList size for(int i = 0 ; i < linkedListColors.size() ; i++ ){ //get the current element using the get method System.out.println( linkedListColors.get(i) ); } } } |
Output
1 2 3 |
Red Green Blue |
This example is a part of the Java LinkedList tutorial.
Please let me know your views in the comments section below.