Java ArrayList size() Method Tutorial

In this section, we will learn what the ArrayList size() method is and how to use it in Java.

What is Java ArrayList size() Method?

The Java ArrayList size() method is used to get the size of an ArrayList object.

When we say size, we mean the current number of elements on the target list.

For example, if there are 4 elements in the target list, then the result of calling this method would be 4. Now we if remove one element of this list and call the method again we’ll get the number 3.

So again, calling the size() method will return the current number of elements in the target list.

Java ArrayList size() Method Syntax:

public int size();

size() Method Parameters:

The method does not take an argument.

size() Method Return Value:

The return value of this method is of type integer and is equal to the current number of elements in the target list object.

size() Method Exceptions:

The method does not throw an exception.

Example: using ArrayList size() method

import java.util.List; 
import java.util.ArrayList; 

public class Main {

    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println("The size of the list before calling the clear method: "+list.size());
        list.clear();
        System.out.println("The size of the list is: "+list.size());
    }
}

Output:

The size of the list before calling the clear method: 3

The size of the list is: 0

Here, as you can see, at first the target list had 3 elements, but then we’ve called the clear() method to clear all the elements of this list and as a result we got 0 when called the size() method again.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies