java 中 类 的内存分配

Memory allocation for classes in java

这是一个有效的 java 代码,用于实现 trie 数据结构。

class TrieNode {
TrieNode[] arr;
boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
    this.arr = new TrieNode[26];
}

我不明白的是内存分配是如何工作的

TrieNode[] arr;

代码。如果是这样的话

class TrieNode {
    int[] arr;
    boolean isEnd;
    // Initialize your data structure here.
    public TrieNode() {
        this.arr = new int[26];
    }

我知道这会为 26 个整数分配内存。 如果您能解释第一个代码的内存分配是如何工作的,那就更好了。 (在编译器的角度)

编辑:抱歉,如果我的问题是 unclear.What 我问的是我们在

中创建包含 26 个元素的数组
new TrieNode[26];

分配了多少内存?

直到你没有调用new没有内存分配完成。

所以TrieNode[] arr;作为以后的参考。 只有当你调用构造函数时,Java才会分配内存并在arr.

里面设置引用

链接:

使用你的第一个代码,当你像这样创建 TriNode 对象时

TriNode t = new TriNode();

JVM 将分配内存来存储 arr 元素的 26 个引用和 isEnd 字段的 1 个引用。为了存储引用,JVM 对 32 位 JVM 使用 32 位,对 64 位 JVM 使用 64 位。 创建数组时

new TrieNode[26];

它将分配 26*(64bit/32bit)+1 布尔值,因为它不会创建 TrieNode 对象,而是创建引用数组来存储尚未创建的 TriNode 对象。所以当你初始化数组元素时

arr[0] = new TrieNode();

然后会为TrieNode()对象分配内存,arr[0]会指向这个对象。

So conclusion is JVM will not allocate memory for 26 Trinode objects instead it will allocate memory for their references.