Is there a limit to the number of elements a Java array can contain? If so, what is it?
An array can have a maximum of eight dimensions. You declared an array whose total size is greater than the maximum allowable size. The maximum allowable array size is 65,536 bytes (64K).
Yes, there limit on java array. Java uses an integer as an index to the array and the maximum integer store by JVM is 2^32. so you can store 2,147,483,647 elements in the array.
You can't change the size of the array after it's constructed. However, you can change the number of elements in an ArrayList whenever you want.
Haven't seen the right answer, even though it's very easy to test.
In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
. Once you go beyond that:
public class Foo { public static void main(String[] args) { Object[] array = new Object[Integer.MAX_VALUE - 4]; } }
You get:
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With