Java Set collection - override equals method

前端 未结 5 738
孤城傲影
孤城傲影 2020-12-14 17:08

Is there any way to override the the equals method used by a Set datatype? I wrote a custom equals method for a class called Fee

5条回答
  •  余生分开走
    2020-12-14 17:47

    One solution would be to use a TreeSet with a Comparator.

    From the documentation:

    TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

    This approach would be much faster than using a LinkedList, but a bit slower than a HashSet (ln(n) vs n).

    It's worth noting a one side effect of using TreeSet would be that your set is sorted.

提交回复
热议问题