How do I know the size of ArrayList?

Category: java.util, viewed: 4K time(s).

java.util.ArrayList is a class that can be use to create a dynamic size array. We can add items into and remove items from the ArrayList. Because its content change in size you might want to know the number of elements stored by this list.

To do this you can use the size method. This method returns an int value that tells you the number of elements stored in the ArrayList object. When the list contains more than Integer.MAX_VALUE elements this method returns Integer.MAX_VALUE.

package org.kodejava.example.util;

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

public class ArrayListSize {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Get the number of elements in the list
        int size = list.size();
        System.out.println("List size = " + size);
    }
}