Abstract
- There are two interfaces provided by Java to implement object comparison logic -
java.lang.Comparable<T>
andjava.util.Comparator<T>
java.lang.Comparable<T> | java.util.Comparator<T> | |
---|---|---|
Purpose | Insert 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 Method | int 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 implementsComparable<T>
that compares theStudent
objects based on theirid
- Second, we created a class
AgeComparator
that implementsComparator<T>
that comparesStudent
objects based on theirage
- Lastly, we show how
Collections.Sort()
uses the default comparison implemented withComparable<T>
, and how we can override it with comparison logic implemented withComparator<T>