Java's Comparable<T> interface defines method: compareTo(T other). When your class implements it, you're telling Java how to order objects of that type.
compareTo must return:
- A negative number if
thiscomes beforeother - Zero if they're equal
- A positive number if
thiscomes afterother
class Student implements Comparable<Student> {
String name;
double gpa;
public int compareTo(Student other) {
return Double.compare(this.gpa, other.gpa);
}
}
Double.compare handles edge cases like NaN for you. Without Comparable, calling Collections.sort() on a list of Student objects throws a ClassCastException at runtime.