gpt4 book ai didi

java - Object 类的 equals() 方法

转载 作者:行者123 更新时间:2023-11-29 03:22:52 26 4
gpt4 key购买 nike

我正在阅读 JLS, The Class Object并据此

The method equals defines a notion of object equality, which is based on value, 
not reference, comparison.

但是当我打开Object类的equals方法声明时,是:

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

但是在这里,引用是用引用相等运算符(==)来检查的,这个声明是如何匹配规范的?

最佳答案

参见 javadoc for Object's .equals() :

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).

这意味着,如果您不在类里面覆盖它,这就是您得到的结果。

JLS 的说法仍然是正确的;然而,由实现来定义自己的 .equals() 契约。

(当然,如果您覆盖 .equals(),您也应该覆盖 .hashCode())

关于java - Object 类的 equals() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com