Why it is implied that objects are equal if compareTo() returns 0?

前端 未结 6 1447
野趣味
野趣味 2020-12-16 12:03

Let\'s have a class Person. Person has a name and height.

Equals and hashCode() takes into account only name. Person is comparable (or we implement co

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 12:51

    you can fix it by using name for another comparison when the heights are equal

    @Override
    public int compareTo(Person o) {
        if(height == o.height)return name.compareTo(o.name);
    
        return Integer.compare(height, o.height);
    }
    

    since names are unique this will only return 0 if this.equals(o)

提交回复
热议问题