Maximum array size - type mismatch: cannot convert from long to int

I see that the maximum size of an array can only be the maximum size of Int. Why doesn't Java allow a long-max size array?

long no = 10000000000L;
int [] nums = new int[no];//error here
+5
source share
3 answers

You will need to ask the question “why” to the Java developers. Anyone can only speculate. My guess is that they felt that for each of the two billion elements there should be enough (which, rightly, probably is).

+5
source

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

i.e. 16 GiB spaces for a long [] array.

try to create this ...

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

OUTOFMEMMORY... SO Integer.MAX_VALUE - 5

0
  • int-size 2 31 -1 ( "~ 2 " ). .

  • 2 16 . Java 1995 , 8 . 32- , , , , 2 , . , , , .

  • 32- ints , longs.

  • Arrays are the main internal type, and they are used several times. The length of the long length will require an additional 4 bytes per array for storage, which, in turn, may affect the packing of arrays together in memory, potentially losing more bytes between them. (Even though a longer length will almost never be useful.)

  • If you ever need more than 2 billion items in RAM, you can use an array of arrays.

0
source

All Articles