- All classes inherit from
Object
- Therefore they use the
Object.equals
method until you override it
Object.equals
tests for reference equality, it knows nothing about the fields in your class and cannot test for "value" equality
i.e. to test for value equality you need to override equals and provide your own implementation. As an example:
class Employee{
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
//see comments below for this next line
if (o.getClass() != this.getClass()) return false;
Employee other = (Employee)o;
return other.id == this.id;
}
}
Your override should satisfy the rules of reflexivity, symmetry, transitivity, consistency, and be false
for a null
argument, hence the complexity in the above example. To do this it does:
- a reference check (for efficiency)
- a null check
- either an
instanceof
, or a getClass
check (the choice between these two depends on your definition of equality for subtypes)
- a cast to the same type
- finally, the value field checks
Note also that overriding equals means you should also override hashCode:
@Override public int hashCode()
{
return id;
}