Java ArrayList size()

The size() method returns the number of elements present in the arraylist.

Example

import java.util.ArrayList;

class Main {
  public static void main(String[] args) {
    // create an ArrayList
    ArrayList<Integer> primeNumbers = new ArrayList<>();
    primeNumbers.add(2);
    primeNumbers.add(3);
    primeNumbers.add(5);
    primeNumbers.add(7);
    System.out.println("ArrayList: " + primeNumbers);

    // get the number of elements of arraylist
int size = primeNumbers.size(); System.out.println("Length of ArrayList: " + size);
} } // Output: ArrayList: [2, 3, 5, 7] // Length of ArrayList: 4

Syntax of ArrayList size()

The syntax of the size() method is:

arraylist.size()

Here, arraylist is an object of the ArrayList class.


size() Parameters

The size() method does not take any parameters.


size() Return Value

  • returns the number of elements present in the arraylist.

Example: Get the Length of an ArrayList

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<String> languages = new ArrayList<>();

        // insert element to the arraylist
        languages.add("JavaScript");
        languages.add("Java");
        languages.add("Python");
        System.out.println("ArrayList: " + languages);

        // get the number of elements of arraylist
int size = languages.size(); System.out.println("Length of ArrayList: " + size);
} }

Output

ArrayList: [JavaScript, Java, Python]
Length of ArrayList: 3

In the above example, we have created an arraylist named languages. Here, we have used the size() method to get the number of elements present in the arraylist.

Did you find this article helpful?