1. Overview

Java allows us to create arrays of fixed size or use collection classes to do a similar job.

In this tutorial, we’re going to look at the difference between the capacity of an ArrayList and the size of an Array.

We’ll also look at examples of when we should initialize ArrayList with a capacity and the benefits and disadvantages in terms of memory usage.

2. Example

To understand the differences, let’s first try both options.

2.1. Size of an Array

In java, it’s mandatory to specify the size of an array while creating a new instance of it:

Integer[] array = new Integer[100]; 
System.out.println("Size of an array:" + array.length);

Here, we created an I**nteger array of size 100, which resulted in the below output

Size of an array:100

2.2. Capacity of an ArrayList

Technically, the default capacity (DEFAULT_CAPACITY) of a newly created ArrayList is 10. However, Java 8 changed how this initial capacity is used for performance reasons.

It’s not used immediately and is guaranteed lazily once a new item is added to the list.

So, the default capacity of an empty ArrayList is 0 and not 10 in Java 8. Once the first item is added, the DEFAULT_CAPACITY which is 10 is then used.

Since there is no built-in method to get the default capacity, let’s use reflection to return it:

public static int getDefaultCapacity(ArrayList<?> arrayList) throws Exception {

    if (arrayList == null) {
        return 0;
    }

    Field field = ArrayList.class.getDeclaredField("elementData");
    field.setAccessible(true);

    return ((Object[]) field.get(arrayList)).length;
}

Now, let’s confirm that the default capacity of an empty ArrayList is 0:

@Test
void givenEmptyArrayList_whenGetDefaultCapacity_thenReturnZero() throws Exception {

    ArrayList<Integer> myList = new ArrayList<>();
    int defaultCapacity = DefaultArrayListCapacity.getDefaultCapacity(myList);

    assertEquals(0, defaultCapacity);
}

Next, let’s see what happens when we add a new item to an empty ArrayList:

@Test
void givenEmptyArrayList_whenAddItemAndGetDefaultCapacity_thenReturn10() throws Exception {

    ArrayList<String> myList = new ArrayList<>();
    myList.add("ITEM 1");

    int defaultCapacity = DefaultArrayListCapacity.getDefaultCapacity(myList);

    assertEquals(10, defaultCapacity);
}

The purpose of this change in Java 8 is to save memory consumption and avoid immediate memory allocation.

Now, let’s create an ArrayList with an initial capacity of 100:

List<Integer> list = new ArrayList<>(100);
assertEquals(0, list.size());

As no elements have been added yet, the size is zero.

Now, let’s add an element to the list and check its size:

list.add(10);
assertEquals(10, list.size());

3. Size in Arrays vs. ArrayList

Below are some major differences between the size of an array and the capacity of an ArrayList.

3.1. Modification of Size

Arrays are fixed size. Once we initialize the array with some int value as its size, it can’t change. The size and capacity are equal to each other too.

ArrayList‘s size and capacity are not fixed. The logical size of the list changes based on the insertion and removal of elements in it. This is managed separately from its physical storage size. Also when the threshold of ArrayList capacity is reached, it increases its capacity to make room for more elements.

3.2. Memory Allocation

Array memory is allocated on creation. When we initialize an array, it allocates the memory according to the size and type of an array. It initializes all the elements with a null value for reference types and the default value for primitive types.

ArrayList changes memory allocation as it grows. When we specify the capacity while initializing the ArrayList, it allocates enough memory to store objects up to that capacity. The logical size remains 0. When it is time to expand the capacity, a new, larger array is created, and the values are copied to it.

We should note that there’s a special singleton 0-sized array for empty ArrayList objects, making them very cheap to create. It’s also worth noting that ArrayList internally uses an array of Object references.

4. When to Initialize ArrayList with Capacity

We may expect to initialize the capacity of an ArrayList when we know its required size before we create it, but it’s not usually necessary. However, there are a few reasons why this may be the best option.

4.1. Building a Large ArrayList

It is good to initialize a list with an initial capacity when we know that it will get large. This prevents some costly grow operations as we add elements.

Similarly, if the list is very large, the automatic grow operations may allocate more memory than necessary for the exact maximum size. This is because the amount to grow each time is calculated as a proportion of the size so far. So, with large lists, this could result in a waste of memory.

4.2. Building Small Multiple ArrayLists

If we have a lot of small collections, then the automatic capacity of an ArrayList may provide a large percentage of wasted memory. Let’s say that ArrayList prefers a size of 10 with smaller numbers of elements, but we are only storing 2 or 3. That means 70% wasted memory, which might matter if we have a huge number of these lists.

Setting the capacity upfront can avoid this situation.

5. Avoiding Waste

We should note that ArrayList is a good solution for a flexible-sized container of objects that is to support random access. It consumes slightly more memory than an array but provides a richer set of operations.

In some use cases, especially around large collections of primitive values, the standard array may be faster and use less memory.

Similarly, for storing a variable number of elements that do not need to be accessed by index, LinkedList can be more performant. It does not come with any overhead of memory management.

6. Summary

In this short article, we saw the difference between the capacity of the ArrayList and the size of an array. We also looked at when we should initialize the ArrayList with capacity and its benefits with regards to memory usage and performance.

As always, the example code is available over on GitHub.