Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many indices can a long array support in Java?

Tags:

java

I have to use a long array with an index range from 0 to 33554432.

It gives an error of:

"Exception in thread main java.lang.OutOfMemoryError: Java heap space".

Whereas short array does not give this error. I must use a long array and the same indices, what can I do?

like image 843
Khalid Hussain Avatar asked Feb 03 '26 17:02

Khalid Hussain


1 Answers

You can get a hint by the fact that arrays are accessed using integer literals. Since integer literals only go up to Integer.MAX_VALUE, that's how many indices (and elements) your array can have. arshajii brings up another hint.

Your problem just has to do with the fact that your application doesn't have enough memory to create that many longs but has enough to create that many shorts. Remember that when an array is initialized, its elements are also initialized to a default value. For primitive types, that value is 0 or 0.0. Things to consider (depending on your environment)

Long[] array = new Long[33554432]; // allocation would work
long[] array = new long[33554432]; // allocation would fail

This is because reference types are initialized to null reference and so only the reference takes up space. So you could start adding elements, but it would also eventually fail.

Start your application with more memory.

like image 80
Sotirios Delimanolis Avatar answered Feb 06 '26 07:02

Sotirios Delimanolis