java - 我如何知道可以存储在数组中的元素的最大范围?

标签 java arrays

当我创建一个大小 等于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.

Read more .

关于java - 我如何知道可以存储在数组中的元素的最大范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27422366/

相关文章:

java - 在 joda time 中创建自定义日历

c# - 与索引比较查找数组中的值

javascript - XML 请求的多数组

java - 是否可以在 Java 8 流 API 中定义可选流或类似异常的行为?

java - 帮助!错误: The local variable transactionType may not have been initialized

arrays - 在二维空间中找到一个圆内的所有点

javascript - 在不改变词序的情况下反转字符串中的每个词

ruby - 在 ruby​​ 中使用自动创建插入数组

获取月份和年份的java日期问题

java - 无法在 Java 中验证在 iOS 上签名的数据