Comparable Example in Java
Problem
A class implements Comparable to declare its own natural ordering — a single compareTo() method that says, for any two instances, which one comes first.
Define a Student class that implements Comparable by score, and compare two instances directly.
Java Program
class Student implements Comparable<Student> {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public int compareTo(Student other) {
return Integer.compare(this.score, other.score); // negative, zero, or positive — the sign is what matters
}
}
public class ComparableExample {
public static void main(String[] args) {
Student a = new Student("Ravi", 82);
Student b = new Student("Meera", 91);
int result = a.compareTo(b);
System.out.println(a.name + " compared to " + b.name + ": " + result);
}
}Output
Core Logic
Overriding compareTo() to compare just the score field gives every Student a well-defined natural order, without needing a separate comparator object anywhere.
- 1
class Student implements Comparable<Student>commits the class to providing acompareTo(Student other)method. - 2
Integer.compare(this.score, other.score)returns a negative number, zero, or a positive number depending on whether this object's score is less than, equal to, or greater than the other's. - 3Calling
a.compareTo(b)directly runs that comparison between two specificStudentinstances. - 4The returned int's sign is what matters — a negative result means
ais 'less than'bunder this ordering, not that the scores literally subtract to that value.
Ravi has a score of 82 and Meera has 91; since 82 < 91, a.compareTo(b) returns -1.Key Point: compareTo()'s contract only guarantees the sign of the result, not its exact magnitude — checking for negative/zero/positive is always correct, but relying on the specific number returned (like assuming it's the literal difference) isn't.
Why: A single compareTo() call here just compares two int fields directly — its own cost would grow only if the fields being compared were themselves more expensive to compare, like strings or nested objects.