Reputation: 1533
Trying to get maximum array length. I found on net that maximum array length is actually maximum integer value.
I used in my code this piece of code:
int[] array = new int[Integer.MAX_VALUE]; // 2^31-1 = 2147483647
And i get this kind of error :
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at IntMaxValueArrayLength.main(IntMaxValueArrayLength.java:7)
I also found on internet that 2^31-1 can't be maximum value, that i need to subtract some numbers, i tried to subtract like 100000 but still get the same error.
Upvotes: 4
Views: 1498
Reputation: 31660
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
What this means is that you are creating an array that can't fit in memory. Just because the language lets you create an array that large, doesn't mean it will always fit in memory.
Possible solutions are:
1) Figure out a way to not declare an array quite so large. I'm drawing a blank as to why you'd ever need anything like that. Check out List, which can be sized dynamically.
2) Increase the amount of memory (the size of the heap) you give the VM when it starts. A good discussion takes place in this question.
If you tell us why you need an array that big, maybe we can help you find a way around it with a different data structure or algorithm.
Upvotes: 6