在 Java 程序中,将一个对象设置为等于另一个对象是否正确?更具体地说,我正在研究二叉树,我注意到以下代码:
public Node find(int key)
{
Node current = root;
while(current.iData != key)
{
if(key < current.iData)
{
current = current.leftChild;
} else {
//...
}
}
}
Node current = root;
和 current - current.leftChild;
都将一个对象设置为等于另一个对象。这样对吗?
最佳答案
setting an object equal to another one. Is this right?
不,那是不对的。
实际发生的是,您正在将一个变量的引用更改为另一个对象。
所以:
Node current = root; // "current" will point at the same object as `root`.
和
current = current.leftChild; // "current" will point at the same object as `leftChild`.
注意-
使用 =
分配基本类型与使用 =
分配引用类型时的行为完全不同。
关于java - 我可以在 Java 中将一个对象定义为与另一个对象相等吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991787/