When should a class be Comparable and/or Comparator?

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

    Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.
    Comparator is for objects without a natural ordering or when you wish to use a different ordering.

    0 讨论(0)
  • 2020-11-22 14:29

    Comparable is for providing a default ordering on data objects, for example if the data objects have a natural order.

    A Comparator represents the ordering itself for a specific use.

    0 讨论(0)
  • 2020-11-22 14:33

    The text below comes from Comparator vs Comparable

    Comparable

    A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

    Comparator

    A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 14:38

    Difference between Comparator and Comparable interfaces

    Comparable is used to compare itself by using with another object.

    Comparator is used to compare two datatypes are objects.

    0 讨论(0)
提交回复
热议问题