Is there a limit to the number of elements a Java array can contain? If so, what is it?
Arrays are non-negative integer indexed , so maximum array size you can access would be Integer.MAX_VALUE
. The other thing is how big array you can create. It depends on the maximum memory available to your JVM
and the content type of the array. Each array element has it's size, example. byte = 1 byte
, int = 4 bytes
, Object reference = 4 bytes (on a 32 bit system)
So if you have 1 MB
memory available on your machine, you could allocate an array of byte[1024 * 1024]
or Object[256 * 1024]
.
Answering your question - You can allocate an array of size (maximum available memory / size of array item).
Summary - Theoretically the maximum size of an array will be Integer.MAX_VALUE
. Practically it depends on how much memory your JVM
has and how much of that has already been allocated to other objects.