Comparator and equals()

后端 未结 11 2028
终归单人心
终归单人心 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 17:47

    Yes, as others said above, hashCode() is not secure to use here. But if you dont care about the ordering of objects that are equal in terms of o1.compareTo(o2) == 0, you could do something like:

    public int compare(Foo o1, Foo o2) {
            int res = o1.compareTo(o2);
            if (res == 0 && !o1.equals(o2)) {
                return -1;
            }
            return res;
    }
    

提交回复
热议问题