4

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.

Bacteria
  • 8,406
  • 10
  • 50
  • 67
Miljan Rakita
  • 1,433
  • 4
  • 23
  • 44
  • `java -Xms256M ....` –  Sep 07 '15 at 23:44
  • @user5266804 Really don't understand your answer, please explain me. – Miljan Rakita Sep 07 '15 at 23:46
  • [this](https://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html#wp999527) migh help in detail, or [that](https://blog.42.nl/articles/java-xms-in-practice/) –  Sep 07 '15 at 23:51
  • @user5266804 Didn't you mean `-Xmx`? Anyway, MAX_VALUE is 2,147,483,647, or 2 Gb, and an integer is 4 bytes, so you'd need *more* than 8 Gb. – Andreas Sep 08 '15 at 00:29

1 Answers1

6

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.

Community
  • 1
  • 1
Todd
  • 30,472
  • 11
  • 81
  • 89
  • I just wanted to test whats the maximum size that array can get. At the moment i a trying to do what you told me. As soon as i try it out i will tell you what i got. Thanks for response. – Miljan Rakita Sep 07 '15 at 23:55
  • Could you please tell me how could i check whats the maximum length of array i can get on my application ? – Miljan Rakita Sep 08 '15 at 00:01
  • 2
    @MiljanRakita Such question makes as much sense as "what's the maximum length of a car I can build?". – Natix Sep 08 '15 at 00:22
  • @MiljanRakita It depends on how much memory is assigned to the JVM, and how much has already been used. The question is meaningless, allocate what you *need*. If it fails, run the program again, assigning more memory by using the `-Xmx` flag user5266804 told you about in a comment. – Andreas Sep 08 '15 at 00:26
  • @Andreas Just did what he told me and it helps. Thank you guys, now i got it. – Miljan Rakita Sep 08 '15 at 10:37