Comparator and equals()

后端 未结 11 2005
终归单人心
终归单人心 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:56

    If you have no specific expected ordering for any two given elements, but still want to consider them un-equal, then you have to return some specified ordering anyway.

    As others have posted, hashCode() isn't a good candidate, because the hashCode() values of both elements can easily be equal. System.identityHashCode() might be a better choice, but still isn't perfect, as even identityHashCode() doesn't guarantee unique values either

    The Guava arbitrary() Ordering implements a Comparator using System.identityHashCode().

提交回复
热议问题