Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java override Object equals() method

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.

like image 841
user69514 Avatar asked Feb 23 '10 05:02

user69514


3 Answers

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

like image 145
Dan Passaro Avatar answered Sep 21 '22 21:09

Dan Passaro


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
}
like image 37
pgmura Avatar answered Sep 21 '22 21:09

pgmura


@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;
}
like image 37
twodayslate Avatar answered Sep 21 '22 21:09

twodayslate