我有一个公共类Q5,它有一个嵌套的私有静态类BinTree。在main中,我创建了q5对象,并给出了3个节点来添加到树中。
当我尝试获取根的值时,它会返回最后一个节点的值。(此处应该返回1,而不是返回3(
public class Q5 {
private static BinTree root;
public Q5(int ... args)
{
BinTree binTreeLeftChild,binTreeRightChild,root;
root = new BinTree();
binTreeLeftChild = new BinTree();
binTreeRightChild = new BinTree();
root.value = args[0];
binTreeLeftChild.value = args[1];
binTreeRightChild.value = args[2];
root.left = binTreeLeftChild;
root.right = binTreeRightChild;
}
private static class BinTree
{
private static BinTree left;
private static BinTree right;
private static int value;
public BinTree()
{
// TODO Auto-generated constructor stub
left = null;
right = null;
value = 0;
}
}
public static void main(String[] args)
{
Q5 q5 = new Q5(1,2,3);
System.out.println(q5.root.value);
}
您需要删除BinTree
中的static
标识符,否则该类的所有对象都将共享相同的值
在Q5(int ... args)
中,您有一个私有变量,它隐藏类变量root
。你也需要删除它
更正的代码:
public class Q5 {
private static BinTree root;
public Q5(int ... args) {
BinTree binTreeLeftChild,binTreeRightChild;
root = new BinTree();
binTreeLeftChild = new BinTree();
binTreeRightChild = new BinTree();
root.value = args[0];
binTreeLeftChild.value = args[1];
binTreeRightChild.value = args[2];
root.left = binTreeLeftChild;
root.right = binTreeRightChild;
}
private static class BinTree{
private BinTree left;
private BinTree right;
private int value;
public BinTree() {
// TODO Auto-generated constructor stub
left = null;
right = null;
value = 0;
}
}
...
}
我认为问题出在你的"静态"上。尝试为BinTree使用非静态变量。