Search code examples
javaarraydeque

How could ArrayDeque has unlimited size with an array backup


I read this "Array deques have no capacity restrictions" from here:

https://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html#:~:text=Array%20deques%20have%20no%20capacity,Null%20elements%20are%20prohibited.

However, in the source code I found it's using an array (maximum capacity is Integer.MAX_VALUE), and it will throw exception when growing up:

if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
    if (minCapacity < 0)
        throw new IllegalStateException("Sorry, deque too big");
    return Integer.MAX_VALUE;
}

I'm confused, does ArrayDeque really have unlimited size?


Solution

  • As Thomas already mentioned in his comment, the practical limit is Integer.MAX_VALUE which equals to 2,147,483,647 ~ 68 GB. Thus, the javadoc of ArrayDeque is only correct regarding the theory behind it, but not the actual implementation.

    I cannot think of a scenario, which would justify to use ArrayDeque to its maximum capacity. IMHO it would only be the symptom of a very bad code design and should be avoided.