3

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?

knoight
  • 479
  • 8
  • 18
  • 1
    You could try [increasing the Java heap](http://stackoverflow.com/a/1566026/2071828) but note that `short` is 16bit and `long` is 64bit, you require _a lot_ more space. – Boris the Spider Oct 04 '13 at 19:59
  • 3
    Out of *Memory* - it's not that an Array *can't* contain so many elements, merely that the JVM can't create/allocate an Array that large on the current system (with the supplied JVM options). – user2246674 Oct 04 '13 at 19:59
  • 3
    Do you actually need to store 33 million values in these arrays? Or will most of the cells be empty? Consider using a Map where the key is the numeric index. – Kenster Oct 04 '13 at 19:59
  • Arrays are stored contiguously in Java are they not? Could this be an error due to the fact that there isn't a long enough congious segment of memory (Eg something like a balanced tree or a hashtable might work) – daniel gratzer Oct 04 '13 at 20:02
  • If it seems you are the first to have a problem, think about your solution. Is your way the right solution? But you haven't tell us your problem. – Arne Burmeister Oct 04 '13 at 20:18

3 Answers3

6

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.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
5

The array indexes are int. You get OOM as your default heap size is too small. Try run java with -Xmx512m command line option ( as your array already require 8*33554432 = 268435456, 268 MB)

kofemann
  • 4,217
  • 1
  • 34
  • 39
2

Array range should be within maximum value of int.

According to JLS

Arrays must be indexed by int values. An attempt to access an array component with a long index value results in a compile-time error.

Masudul
  • 21,823
  • 5
  • 43
  • 58