Nick Heiner Nick Heiner - 4 months ago 32
Java Question

When should a class be Comparable and/or Comparator?

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

Dan Dan

The text below comes from Comparator vs 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.


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.