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.