JVM如何为对象分配内存,尽管它们以后可能会增大 [英] How can the JVM allocate memory for objects despite the possibility that they might later grow in size

查看:126
本文介绍了JVM如何为对象分配内存,尽管它们以后可能会增大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,我们在Java中有一个Node类,如下所示:

Consider we have a class Node in java like this:

class Node{
Node prev;
Node next;
}

当我们创建一个新的节点(Node sample = new Node();)时,JVM如何为对象分配足够的内存.将来可能会更改其大小.例如,稍后我可以设置sample.setPrev(new Node()),依此类推.因此,如果JVM考虑该示例对象在内存中的索引从1000到2000,则它的大小可能会更改,并且内存索引2001可能不为空.

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.

推荐答案

堆内存由java对象使用,其中包括:

The heap memory is used by a java object including:

  • 原始字段:整数,字符串,浮点数等.它们在内存中具有固定的长度.
  • 对象字段(如prevnext对象),每个字段都有4个字节,仅用于存储引用.设置sample.setPrev(new Node())时,您的prev将保留对另一个内存空间的引用.
  • 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.

这篇关于JVM如何为对象分配内存,尽管它们以后可能会增大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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