Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java arrays have a maximum size?

Tags:

java

arrays

Is there a limit to the number of elements a Java array can contain? If so, what is it?

like image 238
Lizard Avatar asked Jun 14 '10 15:06

Lizard


People also ask

Is there a size limit array?

An array can have a maximum of eight dimensions. You declared an array whose total size is greater than the maximum allowable size. The maximum allowable array size is 65,536 bytes (64K).

Can an array have more than 5 dimensions Java?

Yes, there limit on java array. Java uses an integer as an index to the array and the maximum integer store by JVM is 2^32. so you can store 2,147,483,647 elements in the array.

Can size of array be increased in Java?

You can't change the size of the array after it's constructed. However, you can change the number of elements in an ArrayList whenever you want.


2 Answers

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 
like image 114
Kevin Bourrillion Avatar answered Sep 22 '22 05:09

Kevin Bourrillion


This is (of course) totally VM-dependent.

Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList, .Hashtable, .AbstractCollection, .PriorityQueue, and .Vector, you can see this claim being repeated:

/**  * Some VMs reserve some header words in an array.  * Attempts to allocate larger arrays may result in  * OutOfMemoryError: Requested array size exceeds VM limit  */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 

which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).

So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8) and "attempts to allocate larger arrays may result in OutOfMemoryError".

(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; which shows that MAX_ARRAY_SIZE does not yet have a real use.)

like image 39
Pacerier Avatar answered Sep 22 '22 05:09

Pacerier