Is there a limit for an array in Java?
Thanks
Is there a limit for an array in Java?
Thanks
Yes, since the index is int
based, the maximum length is equal to Integer.MAX_VALUE
: 2147483647. It's however a lot, you may hit the OutOfMemoryError
sooner than the array size limit.
There are actually two limits. One, the maximum element indexable for the array and, two, the amount of memory available to your application. Depending on the amount of memory available and the amount used by other data structures, you may hit the memory limit before you reach the maximum addressable array element.
Haven't seen the right answer, even though it's very easy to test.
In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
. Once you go beyond that:
public class Foo {
public static void main(String[] args) {
Object[] array = new Object[Integer.MAX_VALUE - 4];
}
}
You get:
Exception in thread "main" java.lang.OutOfMemoryError:
Requested array size exceeds VM limit