How to Find Size or Length of ArrayList in Java with Example

In Java, ArrayList is part of Collection framework. It comes under the hierarchy of List interface. It follows array data structure with resizable size feature.

java.util.ArrayList provides a size() method to find the length or size of the given list. The method returns total number of elements contained in the list. We’ll be using this method to get the length of the list.

Screenshot from 2021 02 05 11 59 09

Java program to find the size of the length of ArrayList

size() method is used to find the number of elements present in the list.

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


public class CalculateArrayListSizeExample {

    public static void main(String[] args) {
        int arrSize;
        List<String> arrayList = new ArrayList<>();
        arrayList.add("element 1");
        arrayList.add("element 2");
        arrayList.add("element 3");
        arrayList.add("element 4");
        arrayList.add("element 5");

        arrSize = arrayList.size();
        System.out.println("This is the size or length of the ArrayList : " + arrSize);

    }
}

Output:

This is the size or length of the ArrayList : 5

Explanation:

In the above code, we created an arraylist of String. Using add method, we added 5 elements and with the help of size() method, we got the length or size of the arraylist. Lastly, we printed it on the output screen.

 

Leave a Reply