Java 对象数组的内存分配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20099771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Memory Allocation for Object Arrays
提问by user2249516
In my computer science course, we were taught that when you create an array, the JVM will allocate the memory automatically depending on the size of the array. For example if you create an integer array with a size of 10, the JVM would allocate 10 * 32 Bits of data to that array.
在我的计算机科学课程中,我们被教导当你创建一个数组时,JVM 会根据数组的大小自动分配内存。例如,如果您创建一个大小为 10 的整数数组,JVM 会为该数组分配 10 * 32 位数据。
My question is, how exactly does this process work when you create arrays of object that have varying sizes? For example a String object. When you create an array of 10 Strings, is any memory actually reserved on the system for these strings, or since they are just pointers, memory allocation isn't necessary?
我的问题是,当您创建具有不同大小的对象数组时,这个过程究竟是如何工作的?例如一个字符串对象。当您创建一个包含 10 个字符串的数组时,系统上是否为这些字符串实际保留了任何内存,或者由于它们只是指针,因此不需要分配内存?
采纳答案by aga
Since the String
is a class which extends the Object
class, and objects in Java are passed (and stored in variables) by reference, the array of strings is an array of references to String
objects. So, when you do
由于String
是一个扩展Object
类的类,并且 Java 中的对象是通过引用传递(并存储在变量中)的,因此字符串数组是对String
对象的引用数组。所以,当你做
String[] a = new String[10];
you're creating an array of references, where the size of every reference (not the object it's pointing to) is already known (32 bits for 32-bit machines, and 64 bits for 64 bits machines).
您正在创建一个引用数组,其中每个引用的大小(不是它指向的对象)都是已知的(32 位机器为 32 位,64 位机器为 64 位)。
Upd:as Jon Skeet said in one of his answersthe size of an actual reference may bethe same as a native pointer size, but it's not guaranteed.
回答by Bert F
int[]
=> array of ints
int[]
=> 整数数组
String []
=> array of pointers to String instances
String []
=> 指向 String 实例的指针数组
int[][]
=> array of pointers to (separate, disparate) int[] arrays
int[][]
=> 指向(单独的,不同的)int[] 数组的指针数组
回答by Anirban Nag 'tintinmj'
Arrays are itself an object in Java so it will be always created in runtime. From Official tutorial:
数组本身是 Java 中的一个对象,因此它将始终在运行时创建。来自官方教程:
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
// create an array of integers
anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialized.
创建数组的一种方法是使用 new 运算符。ArrayDemo 程序中的下一条语句为一个具有足够内存的数组分配 10 个整数元素,并将该数组分配给 anArray 变量。
// 创建一个整数数组
anArray = new int[10];
如果缺少此语句,则编译器会打印如下错误,并且编译失败:
ArrayDemo.java:4:变量 anArray 可能尚未初始化。
Also another answer in StackOverflow.