我对 Java 的“equals”方法有疑问。
我创建了一个名为 Person 的类:
public class Person {
}
我正在比较两个对 Person 的引用。
Person p1 = new Person();
Person p2 = new Person();
System.out.println(p1.equals(p2)); //returns false
如果我添加任何实例变量和 setter 方法来设置实例变量,则“equals”方法返回 true。
任何人都可以解释这种行为吗?
最佳答案
如果您不重写 Object.equals(Object),则默认实现使用对象标识进行比较。 (即,如果对象是内存中的同一对象,则 equals 仅返回 true)。
相关 JavaDoc:Object.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).
Object a = new Object();
Object b = new Object();
System.out.println(a.equals(b)); // Prints 'false'
b = a;
System.out.println(a.equals(b)); // Prints 'true'
正如我在我的一条评论中提到的,方法或字段的添加不应影响 equals 方法的默认实现,必须进行其他操作。
关于java - 添加成员/ setter 时默认 `equals` 的行为会改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846604/