内存分配对象数组 [英] Memory Allocation for Object Arrays

查看:125
本文介绍了内存分配对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的计算机科学课程中,我们被教导,当你创建一个数组,JVM将自动取决于数组的大小分配内存。例如,如果你创建一个大小为10的整数数组时,JVM会分配数据的10 * 32位到该阵列。

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.

我的问题是,究竟怎样,当你创建具有不同大小的对象数组这个过程中的工作?例如,一个String对象。当您创建的10串数组,在系统上实际保留这些字符串的内存,或者因为他们只是指针,内存分配是没有必要的?

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?

推荐答案

由于字符串是它扩展了对象的类类,并在Java对象传递(并存储在变量)引用,字符串数组是引用数组字符串的对象。所以,当你做

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[] a = new String[10];

您正在创建引用数组,其中每一个引用(不是它指向的对象)的大小是已知的(32位机器上,32位,64位机64位)。

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).

UPD:作为乔恩斯基特说在他的答案实际的尺寸之一参考的可能的同一个本地指针大小,但它不能保证。

Upd: as Jon Skeet said in one of his answers the size of an actual reference may be the same as a native pointer size, but it's not guaranteed.

这篇关于内存分配对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆