Comparator and equals()

后端 未结 11 2030
终归单人心
终归单人心 2020-12-16 17:27

Suppose I need TreeSet with elements sorted with some domain logic. By this logic it doesn\'t matter order of some elements that doesn\'t equal so compare metho

11条回答
  •  醉酒成梦
    2020-12-16 18:00

    There is no rule in Java which says that the hash codes of two objects must be different just because they aren't equal (so o1.hashCode() - o2.hashCode() could return 0 in your case).

    Also the behavior of equals() should be consistent with the results from compareTo(). This is not a must but if you can't maintain this, it suggests that your design has a big flaw.

    I strongly suggest to look at the other fields of the objects and use some of those to extend your comparison so you get a value != 0 for objects were equals() == false.

提交回复
热议问题