Search code examples
javainitializationarraylist

What's meant by parameter (int initial capacity) in an arraylist


What's meant by parameter (int initialCapacity) in an ArrayList, I thought it's the number of elements but it didn't work when I did this:

public class MyClass {
    private ArrayList<Integer> arr;
    public MyClass(int n_elements) {
        arr = new ArrayList<Integer>(n_elements);
    }
}

Solution

  • It's the initial capacity, i.e. the number of items that ArrayList will allocate to begin with as the internal storage of items.

    ArrayList can contain "any number of items" (as long you have the memory for it) and when doing large initial insertions you can tell ArrayList to allocate a larger storage to begin with as to not waste CPU cycles when it tries to allocate more space for the next item.

    Example:

    ArrayList<Integer> list = new ArrayList<>(2);
    list.add(10); // size() == 1
    list.add(20); // size() == 2, list is "filled"
    list.add(30); // size() == 3, list is expanded to make room for the third element