When should a class be Comparable and/or Comparator?

前端 未结 11 2623
醉话见心
醉话见心 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:35

    Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

    Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

提交回复
热议问题