How to get the capacity of the ArrayList in Java?

I don't think this is possible. What is your use case? I believe C# ArrayLists have a .capacity property, but the Java ArrayList class doesn't expose this information.

You have the constructor that takes an initial capacity argument, and you have the ensureCapacity() method which you could use to reduce the amount of incremental reallocation.

You also have the trimToSize() method you can use if you are really worried about memory usage.


You can get it by reflection:

public abstract class ArrayListHelper {

    static final Field field;
    static {
        try {
            field = ArrayList.class.getDeclaredField("elementData");
            field.setAccessible(true);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
        try {
            final E[] elementData = (E[]) field.get(arrayList);
            return elementData.length;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

You can get the current capacity of an ArrayList in Java using reflection. Here is an example:

package examples1;

import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Field;

public class Numbers {

    public static void main(String[] args) throws Exception {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        System.out.println(getCapacity(numbers));
    }

    static int getCapacity(List al) throws Exception {
        Field field = ArrayList.class.getDeclaredField("elementData");
        field.setAccessible(true);
        return ((Object[]) field.get(al)).length;
    }
}

This will output: 10

Notes:

  1. getCapacity() method modified from the original at http://javaonlineguide.net/2015/08/find-capacity-of-an-arraylist-in-java-size-vs-capacity-in-java-list-example.html
  2. Note that the default capacity of 10 is granted after the first add to the list. If you try this before adding, you will get an output of 0
  3. To force a capacity without adding, pass it in the constructor like so:

    List<Integer> numbers = new ArrayList<>(20);