Java override Object equals() method
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
@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;
}
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
}