Question

I see that the maximum size of an array can be only maximum size of an Int. Why does Java not allow an array of size long-Max ?

long no = 10000000000L;
int [] nums = new int[no];//error here
Was it helpful?

Solution

You'll have to address the "why" question to the Java designers. Anyone else can only speculate. My speculation is that they felt that a two-billion-element array ought to be enough for anybody (which, in fairness, it probably is).

OTHER TIPS

  1. An int-sized length allows arrays of 231-1 ("~2 billion") elements. In the gigantically overwhelming majority of arrays' uses, that's plenty.

  2. An array of that many elements will take between 2 gigabytes and 16 gigabytes of memory, depending on the element type. When Java appeared in 1995, new PCs had only around 8 megabytes of RAM. And those 32-bit operating systems, even if they used virtual memory on disk, had a practical limit on the size of a contiguous chunk of memory they could allocate which was quite a bit less than 2 gigabytes, because other allocated things are scattered around in a process's address space. Thus the limits of an int-sized array length were untestable, unforeseeable, and just very far away.

  3. On 32-bit CPUs, arithmetic with ints is much faster than with longs.

  4. Arrays are a basic internal type and they are used numerously. A long-sized length would take an extra 4 bytes per array to store, which in turn could affect packing together of arrays in memory, potentially wasting more bytes between them. (Even though the longer length would almost never be useful.)

  5. If you ever do need in-RAM storage for more than ~2 billion items, you can use an array of arrays.

Unfortunately Java does not support arrays with more than 2^31 elements.

i.e. 16 GiB of space for a long[] array.

try creating this...

Object[] array = new Object[Integer.MAX_VALUE - 4];

you should get OUTOFMEMMORY error...SO the maximum size will be Integer.MAX_VALUE - 5

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top