28

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);
    }
}

7 Answers 7

56

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
8
  • 4
    I object to the word "default" in the first sentence. The default number is the size that's allocated if you don't put a number in the parentheses. Nov 13, 2010 at 12:49
  • 2
    @Carl: You are correct. Changed it to initial capacity, as to conform to the Java docs.
    – Patrick
    Nov 13, 2010 at 12:55
  • 4
    To be precise: "any number of items" is limited to Integer.MAX due to the fact that arrays in java are indexed by ints (as of Java 6). Nov 13, 2010 at 17:06
  • @Willi: Well, if you are going to allocate more than 2^31-1 values I believe you are having a memory problem rather than having ArrayList running out of capacity.
    – Patrick
    Nov 14, 2010 at 0:17
  • Integer.MAX is about 2 Billions (not 2^31-1) which takes up to 16GB of RAM (on a 64 Bit Machine) which is not soo big today. Nov 20, 2010 at 23:48
17

Practically speaking, it's how many elements you can add to the ArrayList before it resizes in the background, which can save you some cycles if used correctly.

9

Capacity is the size of the internal storage of the objects. The internal storage is always greater than or equal to the size() of the list (so that it can contain all elements).

public class Main {
    public static void main(String[] args) throws Exception {

        ArrayList<Integer> arr = new ArrayList<>();
        System.out.println("initial size = " + arr.size()); // 0
        System.out.println("initial capacity = " + getCapacity(arr));

        for (int i = 0; i < 11; i++)
            arr.add(i);

        System.out.println("size = " + arr.size()); // 11
        System.out.println("capacity = " + getCapacity(arr));
    }

    static int getCapacity(ArrayList<?> l) throws Exception {
        Field dataField = ArrayList.class.getDeclaredField("elementData");
        dataField.setAccessible(true);
        return ((Object[]) dataField.get(l)).length;
    }
}

Running this gives:

initial size = 0
initial capacity = 10
size = 11
capacity = 16
5

Under the hood, ArrayList is essentially a dynamic array. Every time you instantiate using new Arraylist<>() what's happening is that an array is created to hold the values you want to store whose default capacity, not to be confused with size, is 10.

Every time you add a value that would increase the size beyond capacity a new array is created whose capacity is one more than 150% the previous capacity with the contents of the previous array copied within.

If you have a general idea what size the resulting list will be, or are certain but desire the flexibility afforded from using arraylists over arrays you can set the capacity to prevent this repetitive process of creating new arrays, copying the contents of the old array in the new one, and getting rid of the old one -- which will otherwise increase in occurrences proportional to the size of the list.

1

pardon my English. The question asked is 'what is the meaning or function of the parameter initial capacity in the ArrayList?' If I'm not wrong. I explained that whenever an array is created the default capacity is 10. And I explained that the array resizes itself when the number added had is more than it's the bucket. In case of time complexity, I suggested that perfect capacity should be added. Take a look at this code via Geeks for Geeks:

import java.util.*;

class Student {

    public static void main(String[] arg) throws Exception
    {
        try {

            
            ArrayList<String> numbers
                    = new ArrayList<String>(3);

           
            numbers.add("10");
            numbers.add("20");
            numbers.add("30");

            // Print the ArrayList
            System.out.println("ArrayList: " + numbers);

            
            System.out.println(
                    "Increasing the capacity of ArrayList numbers to store up to 500 elements.");

            numbers.ensureCapacity(500);

            System.out.println(
                    "ArrayList numbers can now store upto 500 elements.");
        }

        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
0

By default, ArrayList is set to nothing less than 10. However, it may take more than the default capacity based on the fact that it can expand. To be on a safer side, it is reasonable to set the initial capacity to avoid another declaration of ArrayList. Hence, the initial capacity is primitive datatype int. it is meant to take the number of lists we are adding.

1
  • 1
    This answer answers nothing. It's hard to read and what more than that - contains wrong information. Look at the accepted answer for comparison. Dec 28, 2021 at 13:19
-1

Arraylist size and capacity are different.

For Example: In below arraylist initial capacity = 3, and size of the list = 0 as there is no elements in the list yet.

ArrayList list = new ArrayList(3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.