The size limit1 on arrays is Integer.MAX_VALUE
so an array index that is a long
makes no sense.
A List
can have more than Integer.MAX_VALUE
elements, but indexing it will be problematic because List::get
takes an int
argument.
So, you will struggle to use either arrays or lists (implemented using List
) for really large data structures.
The solution ... if you really need one ... would be to implement your own List
class with overload or alternative for operations that expose the size and indexing. It would not be trivial.
Another (possibly simpler) approach would be to represent your long[]
as a long[][]
and map the subscripts.
Finally, if you are using long
as a subscript unnecessarily (i.e. the indexes don't need to go beyond Integer.MAX_VALUE
), then:
long arr[] = new long[5];
for (long i = 0l; i < 5l; i++) {
arr[(int) i] = i;
}
1 - This is the theoretical maximum size. 1) You may get an OutOfMemoryError
if you attempt to allocate an array that large. The JVM needs at least length * size(<type>)
bytes of free contiguous storage to allocate an array of <type>
of length length
, where size(<type>)
is the size of a primitive type or a reference. 2) In a 32 bit JVM, you are also limited by the address space dimensions. 3) In recent Hotspot JVMs, the largest array that you can allocate is actually Integer.MAX_VALUE - 5
elements: see Do Java arrays have a maximum size?