3

I know that the initial capacity of an ArrayList is 10. When this limit is exceeded, a new ArrayList is created with the capacity of (oldcapacity * 3 / 2) + 1, and the elements are copied over.

But what is the maximum capacity of an ArrayList?

I was asked this question in an interview. The interviewer was not interested in the default initial capacity, but wanted to know the maximum capacity of an ArrayList.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Javamania
  • 31
  • 2

1 Answers1

3

Look in the source code:

public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

and you will see the relevant part here:

this.elementData = new Object[initialCapacity];

so the array list can at most so many elements as an array can hold.

the next question may arise: but then, how many elements can hold an array?

the answer is: it depends on what VM are you writing the code:

in JDK8:

/**
 * The maximum size of array to allocate.
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

where

 /**
 * A constant holding the maximum value an {@code int} can
 * have, 2<sup>31</sup>-1.
 */
@Native public static final int   MAX_VALUE = 0x7fffffff;
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97