简体   繁体   English

Java如何为新实例(具有String属性)分配内存?

[英]How does Java allocate memory for a new instance (with a String property)?

Assume we have a class: 假设我们有一个班级:

    class Account {
      String name;
      int ID;
    }

Then 然后

a1 = new Account();

a2 = new Account();

Will create 2 variables that point to 2 memory locations storing 2 instances of class Account. 将创建2个变量,指向存储2个Account类实例的2个内存位置。

My question is how Java can know how big these instances are to allocate their memory (Because with String type, we can assign any string to that. For example, a1.name = "Solomon I", a2.name = "Alan" . This will lead to different size of each instance) 我的问题是Java如何知道这些实例分配内存的大小(因为使用String类型,我们可以为其分配任何字符串。例如, a1.name = "Solomon I", a2.name = "Alan" 。这将导致每个实例的大小不同)

Memory location is a 'continuous' string of bytes. 内存位置是一个“连续”的字节串。 Therefore, if I have a1 = new Account() then a2 = new Account() => a1's memory location is fixed ('used memory | a1 | a2') so what will happen if I make a1.name a very long string? 因此,如果我有a1 = new Account()然后a2 =新帐户()=> a1的内存位置是固定的('used memory | a1 | a2')那么如果我将a1.name设为一个非常长的字符串会发生什么? Will a1's memory location extend to a2's memory location? a1的内存位置会扩展到a2的内存位置吗?

Thank you for reading this, please let me know if I have any misconception. 感谢您阅读本文,如果我有任何误解,请告诉我。

name is a String reference (not the actual string). name是String引用(不是实际的字符串)。 It will "point" to a String object when you assign it. 分配时,它将“指向”String对象。

Therefore, as part of your object, java only needs to "allocate" space for the String reference, plus an int, which are constant in size. 因此,作为对象的一部分,java只需要为String引用“分配”空间,加上一个大小不变的int。

The object just holds the reference to other object(member variables). 该对象只保存对其他对象(成员变量)的引用。 So its size will always be fixed. 所以它的大小总是固定的。 So changing the contents of the referred object will not effect the size of the object referring to it. 因此,更改引用对象的内容不会影响引用它的对象的大小。 So you need not worry about the String size and your 'Account' class object will not be effected even if you change the String, as only String reference is stored by the 'Account' class object. 因此,您无需担心字符串大小,即使更改字符串也不会影响“帐户”类对象,因为“帐户”类对象只存储字符串引用。

Hope this has helped you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM