I try to create an array of Integers (i tried with own object but the same happened with int) , with size of 30 million. i keep getting “OutOfMemoryError: Java heap space”
Integer [] index = new Integer[30000000];
for (int i = 0 ; i < 30000000 ; i++){
index[i] = i;
}
i checked the total heap space, using “Runtime.getRuntime().totalMemory()” and “maxMemory()”
and saw that i start with 64 MB and the max is 900+ MB, and during the run i get to 900+ on the heap and crush.
now i know that Integer takes 4 bytes, so even if i multiply 30*4*1000000 i should still only get about 150-100 mega.
if i try with a primitive type, like int, it works.
how could i fix it ?
Java’s int primitive will take up 4 bytes but if you use a ValueObject like Integer it’s going to take up much more space. Depending on your machine a reference alone could take up 32 or 64 bits + the size of the primitive it is wrapping.
You should probably just use primitive ints if space is an issue. Here is a very good SO answer that explains this topic in more detail.