Careeroza
Comparable
Natural Ordering
Comparable<T> gives a class one natural order through compareTo. String, Integer and LocalDate already implement it. compareTo returns:
| Result | Meaning |
|---|---|
| negative | this comes before the other |
| 0 | equal in ordering |
| positive | this comes after the other |
Implementing Comparable
Example
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Ravi", 3), new Student("Asha", 1), new Student("Meena", 2)));
Collections.sort(list); // uses compareTo
System.out.println(list);
System.out.println(new TreeSet<>(list).first());
}
}
class Student implements Comparable<Student> {
final String name;
final int rollNo;
Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.rollNo, other.rollNo); // natural order: by roll number
}
@Override
public String toString() {
return rollNo + ":" + name;
}
}Output
[1:Asha, 2:Meena, 3:Ravi] 1:Asha
Tip: Use Integer.compare(a, b) instead of a - b. Subtraction can overflow for large or negative values and give the wrong sign.