Abstract


java.lang.Comparable<T>java.util.Comparator<T>
PurposeInsert the comparison logic into object.Insert comparison logic into objects that don’t implement java.lang.Comparable<T>.

Overwrite objects that do implement java.lang.Comparable<T> with custom comparison logic.
Comparison Methodint compareTo(T o1, T o2)

Negative
Zero
Positive
int compare(T o1, T o2)

Negative
Zero
Positive

Code Example


  • First, we created a class Student that implements Comparable<T> that compares the Student objects based on their id
  • Second, we created a class AgeComparator that implements Comparator<T> that compares Student objects based on their age
  • Lastly, we show how Collections.Sort() uses the default comparison implemented with Comparable<T>, and how we can override it with comparison logic implemented with Comparator<T>