Java override Object equals() method

后端 未结 9 710
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 07:21

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){

}


        
相关标签:
9条回答
  • 2020-12-19 08:08

    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

    0 讨论(0)
  • 2020-12-19 08:13

    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();
    }
    
    0 讨论(0)
  • 2020-12-19 08: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;
    }
    
    0 讨论(0)
  • 2020-12-19 08:20

    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.

    0 讨论(0)
  • 2020-12-19 08:20

    If you plan to create subclasses of Person, use something like

    if(obj!=null && obj.getClass() == Person.class)

    rather than instanceof

    0 讨论(0)
  • 2020-12-19 08:21

    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 ---
    
    }
    
    0 讨论(0)
提交回复
热议问题