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){
}
It's actually more complicated than you might think. Have Eclipse (or whatever IDE you're using) auto-generate an equals
method; you'll see it contains a few checks and casts before it does a comparison.
Also see here: http://www.javapractices.com/topic/TopicAction.do?Id=17
I know this is answered, but in my travels I have found this the most efficient way to override the comparison of an object to make sure it happens the same globally:
@Override
public boolean equals(Object o) {
return o instanceof Person && this.getSomeMagicalField().equals(((Person) o).getSomeMagicalField());
}
or if you are not comparing strings:
@Override
public boolean equals(Object o) {
return o instanceof Person && this.getSomeMagicalField() == (Person) o).getSomeMagicalField();
}
@Override
public boolean equals(Object o)
{
if (o instanceof Person)
{
Person c = (Person) o;
if ( this.FIELD.equals(c.FIELD) ) //whatever here
return true;
}
return false;
}
Take a look at Regarding Object Comparison.
Be aware that if you override equals()
you must also override hashCode()
. The equals/hashCode contract is that if two objects are equal they must have the same hash code.
If you plan to create subclasses of Person, use something like
if(obj!=null && obj.getClass() == Person.class)
rather than instanceof
One more point may be good to know that after you override equals()
method (and also hashcode()
) method you can to compare two objects of same class like follows:
Person p1 = new Person();
Person p2 = new Person();
....
if ( p1.equals( p2 ) )
{
// --- Two Persons are equal, w.r.t the fields you specified in equals method ---
}