java - 我可以在 Java 中将一个对象定义为与另一个对象相等吗?

标签 java

在 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/

相关文章:

编译时在代码中替换Java静态最终值?

java - 所有 @Before 和 @After 场景方法都会在场景执行之前被调用

java - Spring 多个打开的连接

java - 用括号解析负数

java - 基于复选框 JTable 使特定单元格可编辑

java - OpenCV 检测 ROI,创建 submat 并复制到原始 mat

java - 什么时候需要回溯?

java - 当 activemq 连接丢失时,Spring Context 关闭 Camel 路由

c - 尝试理解 JNI.h 中的 C 函数调用

java - 截图: RasterFormatException (y+ height) is outside Raster