When should a class be Comparable and/or Comparator?

前端 未结 11 2509
醉话见心
醉话见心 2020-11-22 14:11

I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?

11条回答
  •  悲哀的现实
    2020-11-22 14:14

    Comparable is usually preferred. But sometimes a class already implements Comparable, but you want to sort on a different property. Then you're forced to use a Comparator.

    Some classes actually provide Comparators for common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER.

提交回复
热议问题