Size of ArrayList
Its very important to know the size of ArrayList as it is required in most of the times while coding
We have size() method in ArrayList class which helps us to determine the size of ArrayList
Size is the number of elements in that ArrayList
- public int size()
public int size()
Example :
- import java.util.*;
- public class ArrayListSize {
- public static void main(String[] args) {
- ArrayList<Integer> list = new ArrayList<Integer>();
- list.add(14);
- list.add(7);
- list.add(21);
- list.add(28);
- list.add(35);
- list.add(42);
- System.out.println("Initial Size of ArrayList: "+list.size());
- list.remove(1);
- list.remove(2);
- System.out.println("Size after removing 2 elements: "+list.size());
- System.out.println("Final ArrayList after removal of 2 elements: ");
- for(int ele: list){
- System.out.println(ele);
- }
- }
- }
import java.util.*; public class ArrayListSize { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(14); list.add(7); list.add(21); list.add(28); list.add(35); list.add(42); System.out.println("Initial Size of ArrayList: "+list.size()); list.remove(1); list.remove(2); System.out.println("Size after removing 2 elements: "+list.size()); System.out.println("Final ArrayList after removal of 2 elements: "); for(int ele: list){ System.out.println(ele); } } }
Here Size just tells how many elements are present in the arraylist
Don’t get confuse size with capacity in the Arraylist, we will talk about capacity separately
Just remember Size() returns number of elements present in ArrayList
Remember size() is a method , not a variable in the ArrayList class.