How do I override the equals method in the object class?
i.e I have
class Person{
//need to override here
public boolean equals (Object obj){
}
I prefer the simpler, null-safe(r) Objects.equals
for any field type:
@Override
public boolean equals(Object o) {
if (o instanceof Person) {
Person p = (Person) o;
return Objects.equals(p.FIELD, this.FIELD);
}
return false;
}
The only reason to use getClass()
rather than instanceof
is if one wanted to assert that both references being compared point to objects of the exact same class rather than objects implementing the same base class.
Say we have an Employee
e and a Manager
m (extends Employee
).
m instanceof Employee
would yield true, m.getClass() == Employee.class
would return false.
In some cases the latter might be preferred, but rarely in case of comparison of instances in equals()
or hashCode()
methods.
You can cast it inside the method, just make sure that is of the right type using instance of
if(obj instanceof Person)
{
Person otherPerson = (Person) obj;
//Rest of the code to check equality
}
else
{
//return false maybe
}