1

The question: 'what's the maximum array length in java' has been asked over and over - this is not this question. As many answers point out, (some) classes in java.util define a constant MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8. There is nothing (as far as I know) in JLS backing that limit, so it seems to me it's a result of a 'verify in practice on some JVMs and add 50% safety margin' approach.

So, the limit is not guaranteed to work for one, and the user is not safe from OutOfMemoryError, even with adjusted heap, due to other objects and contingency requirement, that's two.

My question is thus: why at all introduce that check just to throw a different exception when it doesn't guarantee the contract of this-and-this exception thrown when attempting to grow the collection to over that size? It doesn't make a difference for the caller if they'll get a different exception in some cases than others - in fact, it is slightly annoying, because knowing the allocated structure is large, one can catch the OutOfMemoryError (yes, not a standard practice, but arrays this big aren't standard either), while IllegalStateException is quite ambigous.

Turin
  • 2,208
  • 15
  • 23
  • Not a duplicate! I Please read before marking duplicate or downvoting, as the question is stated plainly in the last paragraph, while the first states while it is not the same question. Bolded out just for you. Duh. – Turin May 12 '19 at 12:54
  • Related: [Java 8 Arraylist hugeCapacity(int) implementation](https://stackoverflow.com/questions/35582809/java-8-arraylist-hugecapacityint-implementation). – MC Emperor Sep 10 '19 at 08:27
  • Which classes are you talking about? `java.util.ArrayList` defines `MAX_ARRAY_SIZE` with a reason stated in the source code, and does not throw `IllegalStateException` instead of `OutOfMemoryError` when it is exceeded. – user207421 Sep 10 '19 at 08:38
  • The `OutOfMemoryException` is thrown if the requested grow size became negative; this is to avoid a `NegativeArraySizeException` being thrown. – MC Emperor Sep 10 '19 at 08:59

1 Answers1

0

First of all, one could catch a RunTimeException.

An indiscriminate OutOfMemoryException indeed yields the intuitive association of something exceded the memory limits. "When OutOfMemoryException" increase the jvm memory option.

However an IllegalStateException points to something conceptually wrong.

  1. It better points to the cause.
  2. The error is in allowing so many elements to be collected. "Do not store house addresses in a Map."
  3. Increasing the memory would not be a solution to the limited size of arrays. In fact any other exception would be misleading, OutOfMemory, IndexOutOfBounds.
  4. An OutOfMemoryException can be caused by endless recursion and other things, and theoretically just happen to be thrown in a collection.
  5. A stack trace sometimes is not available.
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138