为什么我不能创建一个大尺寸的数组? [英] Why I can't create an array with large size?
问题描述
为什么不能创建一个最大 int 大小的数组?
Why it is impossible to create an array with max int size?
int i = 2147483647;
int[] array = new int[i];
我找到了这个解释:
Java 数组是通过 32 位整数访问的,因此最大理论数组大小为 2147483647 个元素.
Java arrays are accessed via 32-bit ints, resulting in a maximum theoretical array size of 2147483647 elements.
但是正如您所看到的,我的代码不起作用.也无法创建一个size的数组
But as you can see my code doesn't work. It is also impossible to create an array with size
new int[Integer.MAX_VALUE - 5];
技术细节
- 64 位 HotSpot JVM
- OSX 10.10.4
OutOfMemoryError: Java heap space
表示您的数组不适合 Java 堆空间.为了解决这个问题,您可以使用 JVM 选项-Xmx
来增加最大堆大小.还要考虑到对象的最大大小不能大于最大堆代.OutOfMemoryError:请求的数组大小超出 VM 限制
表示超出了特定于平台的大小:- 上限由用于描述数组中索引的大小类型的限制设置,因此理论上的数组大小受
2^31-1=2147483647
个元素的限制.莉> - 另一个限制是特定于 JVM/平台的.根据 第 10 章:Java 语言规范的数组,JavaSE 7 版对数组长度没有严格限制,因此可以在不违反 JLS 的情况下减小数组大小.
OutOfMemoryError: Java heap space
means your array does not fit into java heap space. In order to solve you can increase the maximum heap size by using JVM option-Xmx
. Also take into account that the maximum size of object cannot be larger than the largest heap generation.OutOfMemoryError: Requested array size exceeds VM limit
means platform-specific size was exceeded:- the upper bound limit is set by the restrictions of the size type used to describe an index in the array, so theoretical array size is limited by
2^31-1=2147483647
elements. - the other limit is JVM/platform specific. According to chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition there is no strict limit on array length, thus array size may be reduced without violating JLS.
在 HotSpot JVM 中,数组大小受内部表示的限制.在 GC 代码中,JVM 将堆字中的数组大小作为
int
传递,然后从堆字转换回jint
这可能会导致溢出.因此,为了避免崩溃和意外行为,最大数组长度受到 (最大大小 - 标题大小).其中 标头大小 取决于用于构建您正在运行的 JVM(Linux 为 gcc,macos 为 clang)和运行时设置(如UseCompressedClassPointers
)的 C/C++ 编译器.例如在我的 linux 上:In HotSpot JVM array size is limited by internal representation. In the GC code JVM passes around the size of an array in heap words as an
int
then converts back from heap words tojint
this may cause an overflow. So in order to avoid crashes and unexpected behavior the maximum array length is limited by (max size - header size). Where header size depends on C/C++ compiler which was used to build the JVM you are running(gcc for linux, clang for macos), and runtime settings(likeUseCompressedClassPointers
). For example on my linux:- Java HotSpot(TM) 64 位服务器 VM 1.6.0_45 限制
Integer.MAX_VALUE
- Java HotSpot(TM) 64 位服务器 VM 1.7.0_72 限制
Integer.MAX_VALUE-1
- Java HotSpot(TM) 64 位服务器 VM 1.8.0_40 限制
Integer.MAX_VALUE-2
这篇关于为什么我不能创建一个大尺寸的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- the upper bound limit is set by the restrictions of the size type used to describe an index in the array, so theoretical array size is limited by
- 上限由用于描述数组中索引的大小类型的限制设置,因此理论上的数组大小受
PS
为什么 -5
实际上?
推荐答案
理论
有两种可能的例外:
Theory
There are two possible exceptions: