Is there a limit to the number of elements a Java array can contain? If so, what is it?
This is (of course) totally VM-dependent.
Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList, .Hashtable, .AbstractCollection, .PriorityQueue, and .Vector, you can see this claim being repeated:
/** * 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;
which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).
So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8
) and "attempts to allocate larger arrays may result in OutOfMemoryError".
(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; which shows that MAX_ARRAY_SIZE
does not yet have a real use.)