Java override Object equals() method

后端 未结 9 722
被撕碎了的回忆
被撕碎了的回忆 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: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();
    }
    

提交回复
热议问题