3 回答
TA贡献1863条经验 获得超2个赞
让我们逐行剖析这段代码:
Node root = new Node();
您创建了一个新Node对象。此对象有一个children长度为 1的数组。由于您尚未分配任何内容children,因此该数组包含单个元素null。
Node next = root.children[0];
正如我所说,children[0]是空的,所以next现在是空的。请注意,在这一行中,您没有使它next 始终指向与children[0]. 你只发next点一样的东西children[0]指向那个时候。
root.children[0] = new Node();
现在children[0]被分配了一个非空值。请注意,这并不会改变价值next。
TA贡献2012条经验 获得超12个赞
像这样考虑,我将内存中的对象标记为 {},将引用标记为 -> 所以你开始next = root.children[0],此时root.children[0] -> null,它指向内存中的任何内容,没有对象,所以接下来 -> 空。
然后你做了,root.children[0] -> {a new Node}但 next 仍然next -> null没有指向同一个对象,它不是 的快捷方式root.children[0],它不是next -> root.children[0] -> {a new Node},next 指向什么
如果你有root.children[0] -> {a new Node},然后做next = root.children[0],那么 next 会指向next -> {a new Node},但如果你现在做,root.children[0] = new Node()它会导致root.children[0] -> {a newer Node} 并且 next不会指向这个较新的节点
当您将对象的引用分配给变量时,该变量不会总是指向内存中的相同地址,通过new Node()在内存中的某处创建一个新对象并使用 = 告诉变量指向该新分配的对象
TA贡献1828条经验 获得超6个赞
目前,root.children[0]只有引用而不是对象。因此,您需要首先将子节点添加到根节点,然后在我更改为以下代码时进行分配。
public class MyClass {
public static void main(String args[]) {
Node root = new Node();
root.children[0] = new Node();
Node next = root.children[0];
System.out.println(root.children[0]);
System.out.println(next);
}
public static class Node {
Node[] children = new Node[1];
}
}
添加回答
举报
