Behavior of default `equals` changes when member/setter is added?
I have a question about the Java "equals" method.
I created a class called Person:
public class Person {
}
And I am comparing two references to Person like this.
Person p1 = new Person();
Person p2 = new Person();
System.out.println(p1.equals(p2)); //returns false
If I add any instance variable and setter method to set the instance variable, then the "equals开发者_如何学Python" method returns true.
Can anybody explain this behavior?
If you do not override Object.equals(Object) then the default implementation uses the objects identity for comparison. (i.e. equals only returns true if the objects are the same object in memory).
Relevant JavaDoc: Object.equals
Excerpt:
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'
As I mentioned in one of my comments the additions of methods or fields should not affect the default implementation of equals method, something else must be going on.
p1
and p2
are two different references, that's why. It will return false
unless you have your own equals
method. It doesn't matter if you have instance variable or not.
精彩评论