By using size()
method of ArrayList
class we can easily determine the size of the ArrayList. This method returns the number of elements of ArrayList.
public int size()
Example:
package beginnersbook.com; 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
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.