Nick Heiner Nick Heiner - 1 month ago 6
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
Answer

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.

Comments