当我创建一个大小 等于Integer 的数组时。MAX_VALUE
public static void main(String[] args) {
int[] array = new int[Integer.MAX_VALUE]; // This gives an Error
}
我得到了这个错误:
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds
VM limit at com.arrays.TimeArray2.main(TimeArray2.java:6)
直到现在我才知道 Java 中的数组最多可以存储 2,147,483,647 或 2^31 个值。
所以我在 Google 上查找了这背后的原因,并在 stackoverflow.com 上找到了这个问题:Do Java arrays have a maximum size? .
该讨论的公认答案是:
In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
另一个流行的答案是:
Some VMs reserve some header words in an array. The maximum "safe" number would be
2,147,483,639 (Integer.MAX_VALUE - 8). Attempts to allocate larger arrays may
result in java.lang.OutOfMemoryError.
If you have the source code for the java classes, checkout
java.util.ArrayList.class (line 190):
但是,以上都不是真的(至少对我来说不是)。当我以上述两个值之一的范围运行程序时,我仍然不断收到相同的错误。
不仅如此,即使使用以下一组值也会弹出错误:
int[] array = new int[Integer.MAX_VALUE-10]; // Error
int[] array = new int[Integer.MAX_VALUE-100]; // Error
int[] array = new int[Integer.MAX_VALUE-1000]; // Error
int[] array = new int[2147483647]; // Error
int[] array = new int[214748364]; // Error
所以,最后我的问题是:
1) 最大值是多少?不。数组可以在 Java 中存储哪些元素?
2) 如何确保它能够在满足流行的 Java 标语一次编写随处运行的所有平台(或多个 JVM 实现)上运行?
最佳答案
Java has got a limit on the maximum array size your program can allocate. The exact limit is platform-specific but is generally somewhere between 1 and 2.1 billion elements.
java.lang.OutOfMemoryError 的原因
The error is thrown by the native code within the JVM. It happens before allocating memory for an array when JVM performs a platform-specific check: whether the allocated data structure is addressable in this platform.
关于java - 我如何知道可以存储在数组中的元素的最大范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27422366/