You can find the length (or size) of an ArrayList in Java using size() method. The size() method returns the number of elements present in the ArrayList.
Syntax of size() method:
public int size()
Program to find length of ArrayList using size()
In this program, we are demonstrating the use of size()
method. As you can see, when arraylist is created, the size of it is zero. After adding few elements to the arraylist, the size of arraylist changed to 5 as we have done 5 additions using add() method. We then removed two elements from the arraylist using remove() method and printed the size again, which came as 3. This shows that the size()
method returns the number of elements in a arraylist present at that particular moment of time.
import java.util.ArrayList; public class Details { public static void main(String [] args) { ArrayList<Integer> al=new ArrayList<Integer>(); System.out.println("Initial size: "+al.size()); al.add(1); al.add(13); al.add(45); al.add(44); al.add(99); System.out.println("Size after few additions: "+al.size()); al.remove(1); al.remove(2); System.out.println("Size after remove operations: "+al.size()); System.out.println("Final ArrayList: "); for(int num: al){ System.out.println(num); } } }
Output:
Initial size: 0 Size after few additions: 5 Size after remove operations: 3 Final ArrayList: 1 45 99
Another Example:
This is another example, where we have an arraylist of string type and we are using the size() method to find the length of arraylist after various add()
and remove()
operations.
import java.util.ArrayList; public class JavaExample { public static void main(String [] args) { ArrayList<String> cityList=new ArrayList<>(); //adding elements to the arraylist cityList.add("Delhi"); cityList.add("Jaipur"); cityList.add("Agra"); cityList.add("Chennai"); //displaying current arraylist and size System.out.println("ArrayList: "+cityList); System.out.println("ArrayList size: "+cityList.size()); //removing an element from arraylist cityList.remove("Delhi"); //print arraylist and size System.out.println("ArrayList: "+cityList); System.out.println("ArrayList size: "+cityList.size()); } }
Output:
ArrayList: [Delhi, Jaipur, Agra, Chennai] ArrayList size: 4 ArrayList: [Jaipur, Agra, Chennai] ArrayList size: 3
Recommended articles:
Vaibhav Chintawar says
after removing al.remove(2); still why we are getting an output which is at 3rd position al.add(45)
venkatesh says
Because when we remove element at first index, the element 45 moves to index 1 and 44 moves to index 2.Now when we remove(2) 44 will be deleted.