Object中的equals实现

The equals implementation in Object

我在阅读 Java 中的 equals 方法,我听到有人说 == 测试引用相等性(它们是否是同一个对象)。 .equals() 测试值是否相等(它们在逻辑上是否 "equal")。

我相信这是真的,但是,如果您查看 .equals() 的源代码,它只是遵从 ==

来自对象 class:

    public boolean equals(Object obj) {
    return (this == obj);
}

现在我很困惑。我看到的是我们正在测试当前对象是否具有对显式参数的相同引用。它测试引用相等性还是值相等性?

来自 the Javadoc:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Object 是最终的基础 class,这是它可以提供的 equals 的唯一定义。没有可跨实例比较的字段,因此实例只能等于其自身。


您在评论中说:

I would like to know about String comparison I see people use it all the time

您的问题是关于 Object,而不是 StringString 覆盖 equals,因为 Objectequals 的定义不适合 String。因此,String 定义了它自己的(与 equals 实现所需的语义一致)。

对象没有可与之比较的值。

但为了有意义,它必须提供 equals() 或 hashCode() 等方法的实现。

因此,准确地说:从 Object 派生的 类 应该覆盖 equals(),以防它们用 "value semantics" 替换引用相等性。