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 want to convert the parameter obj to a type Person, but if I do (Person) obj it won't work.
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
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
}
@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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With