【发布时间】:2016-05-03 10:18:26
【问题描述】:
这个问题非常抽象,因此很难描述或搜索,这就是我在这里的原因。然而,这是一个非常简单的问题。
我有以下课程:
class Node<T>
{
Comparable data;
Node<T> left, right;
public Node(Comparable data)
{
this.data = data;
}
}
如果我有会发生什么:
/*
* Imagine this root looks like the following:
* 10 (root)
* / \
null null
*/
Node root;
// Imagine we are inside of the insert method and this
// is the current value that is going to be inserted.
int valueIAmTryingToInsert = 5;
// As we see from the tree above, "child" WILL be null.
Node child = (valueIAmTryingToInsert.compareTo(root.data) < 0 ? root.left : root.right);
if (child == null)
{
child = new Node(data);
return true;
}
// Recursive statement would happen here.
请注意,child 是指向root 的左子或右子的指针。但是,如果我实例化 child 指向的节点会发生什么?调用child = new Node(data);后,树目前是不是这样:
10 (root)
/ \
5 null
如果它不看起来像那样,请解释原因。因为我的理解是即使Node child 为空,指针仍然 指向root 的其中一个孩子。我很确定这不起作用,因为我的编辑在声明child = new Node(data); 中强调了child 并声称The value new Node(data) assigned to 'child' is never used(即使它正在被使用)。
【问题讨论】:
-
这实际上是一种更简单的方式来描述我的问题。为什么THIS 会产生空指针异常? second 指向 first,它最初为 null,但随后成为一个初始化对象,因此应该正确指向它。
-
根节点还没有初始化?所以 root.data 会抛出 NPE。另外,您创建了一个子节点但尚未附加到根节点?
-
根据您的评论,当您调用“new”时,您正在为该对象在内存中创建一个 NEW 引用。 Null 是没有参考的。这就是为什么, second 和 first 指向 null,但是当你实例化 first 时, second 仍然指向 null,然后 second.x 抛出 NPE
-
@MinhKieu 我不想写出一棵完全成熟的树,所以就假装
root已经初始化并且有很多孩子,等等。 -
@aquiros 但是
second指向变量first。这应该意味着无论first发生什么,它都应该记住first在内存中的位置。你是说当我打电话给first = new ...时,它实际上改变了内存位置,不再是以前的位置了吗?
标签: java data-structures binary-tree nodes