简体   繁体   中英

Maximum array length in java Integer.MAX_VALUE is not working

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM