How can the JVM allocate memory for objects despite the possibility that they might later grow in size

天大地大妈咪最大 提交于 2019-12-11 11:01:33

问题


Consider we have a class Node in java like this:

class Node{
Node prev;
Node next;
}

when we create a new Node (Node sample = new Node();) how does the JVM allocate enough memory for the object. Its size might change in the future. For example, later I can set sample.setPrev(new Node()) and so on. so if JVM considers indexes from 1000 to 2000 in memory for this sample object then it's size might change and the memory index 2001 might not be empty for our use.


回答1:


The heap memory is used by a java object including:

  • Primitive fields: Integer, String, Float, etc. They have fixed length in memory.
  • Object fields(like your prev and next object),they have 4 bytes for each, just used to store reference only. When you set sample.setPrev(new Node()), your prev will keep a reference to another memory space.



回答2:


All Java objects have a fixed size that is known at the point of construction of the object. No operations your code can perform can cause an object to grow and need more space.

To understand why that is so, you must understand the difference between an object and an object-reference. In Java you can never access an object directly. You can access objects only through an object-reference. An object-reference is like (but not the same as) a memory address. All object references have the same size (or maximum possible size) regardless of the size of object they refer to. If your setPrev method was

void setPrev(Node p) {
   this.prev = p;
}

that changes the object-reference this.prev to refer to (point to) the same object as the object-reference p. It does not copy the object referred to by p into the this object.



来源:https://stackoverflow.com/questions/53203194/how-can-the-jvm-allocate-memory-for-objects-despite-the-possibility-that-they-mi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!