假设我有自己的类(class)
public class MyObj { /* ... */ }
它有一些属性和方法。它不实现equals,不实现hashCode。
一旦我们调用equals和hashCode,默认的实现是什么?来自对象类?它们是什么?默认 equals 将如何工作?默认 hashCode 将如何工作以及返回什么? == 只会检查它们是否引用同一个对象,所以很简单,但是 equals() 和 hashCode() 方法呢?
最佳答案
是的,默认实现是 Object 的(一般来说;如果您从重新定义 equals 和/或 hashCode 的类继承,那么您将使用该实现代替)。
来自文档:
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).
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
关于java - 默认 .equals 和 .hashCode 将如何适用于我的类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178997/