Java override Object equals() method

后端 未结 9 711
被撕碎了的回忆
被撕碎了的回忆 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:24

    I prefer the simpler, null-safe(r) Objects.equals for any field type:

    @Override
    public boolean equals(Object o) {
        if (o instanceof Person) {
            Person p = (Person) o;
            return Objects.equals(p.FIELD, this.FIELD);
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-12-19 08:25

    The only reason to use getClass() rather than instanceof is if one wanted to assert that both references being compared point to objects of the exact same class rather than objects implementing the same base class.

    Say we have an Employee e and a Manager m (extends Employee).

    m instanceof Employee would yield true, m.getClass() == Employee.class would return false.

    In some cases the latter might be preferred, but rarely in case of comparison of instances in equals() or hashCode() methods.

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

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