Comparator and equals()

后端 未结 11 2011
终归单人心
终归单人心 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条回答
  •  Happy的楠姐
    2020-12-16 17:47

    int res = o1.compareTo(o2);
    
    if(res == 0 || !o1.equals(o2)){
        return o1.hashCode() - o2.hashCode();
    }
    

    Can be problematic, since if 2 objects are equal (i.e. in your res == 0) then these 2 objects return the same hashcode. Hashcodes are not unique for every object.


    Edit @Stas, The System.identityHashCode(Object x); still won't help you. The reason is described on the javadoc:

    Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

提交回复
热议问题