ArrayList size() Method in Java with Examples (original) (raw)

Last Updated : 10 Dec, 2024

In Java, the **size() method is used to get the number of elements in an ArrayList.

**Example 1: Here, we will use the **size() method **to get the number of elements in an ArrayList of integers.

Java `

// Java program to demonstrate the use of // size() method for Integer ArrayList import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of Integers
    ArrayList<Integer> n = new ArrayList<>();

    // Adding elements to the ArrayList
    n.add(21);
    n.add(22);
    n.add(23);

    // Getting and printing the 
    // size of the ArrayList
    int s = n.size();
    System.out.println("" + s);
}

}

`

Syntax of ArrayList size() Method

public int size()

**Returns Value: This method returns the number of elements in the list.

**Example 2: Here, we use the size() method **to get the number of elements in an ArrayList of **strings.

Java `

// Java program to demonstrate the use of // size() method for String ArrayList import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    // Creating an ArrayList of Strings
    ArrayList<String> f = new ArrayList<>();

    // Adding elements to the ArrayList
    f.add("Apple");
    f.add("Banana");
    f.add("Orange");

    // Getting and printing the 
    // size of the ArrayList
    int s = f.size();
    System.out.println("" + s);
}

}

`

**Example 3: Here, we demonstrate **how to use the size() method on an ArrayList that stores objects.

Java `

// Java program to demonstrate the use of // size() method for Object ArrayList import java.util.ArrayList;

class Person { String n; int a;

Person(String n, int a) {
    this.n = n;
    this.a = a;
}

}

public class Main { public static void main(String[] args) {

    // Creating an ArrayList of Person objects
    ArrayList<Person> p = new ArrayList<>();

    // Adding elements (objects) to the ArrayList
    p.add(new Person("Ram", 22));
    p.add(new Person("Shyam", 25));

    // Getting and printing the 
    // size of the ArrayList
    int s = p.size();
    System.out.println("" + s);
}

}

`