Implementing Comparable in a Custom Class
What you'll learn: How to add natural ordering to your own classes by implementing the Comparable interface.
Why Implement Comparable?
You've learned that natural ordering allows objects to be sorted automatically. But how do you give your own custom classes this ability? That's where implementing Comparable comes in.
Think of it like teaching your class the rules of "greater than" or "less than" for its type. A Person class doesn't naturally know how to compare itself to another Person—is it by age? Name? You decide by implementing Comparable.
The Implementation Pattern
To make your class comparable, you need two things:
- Add
implements Comparable<YourClass>to your class declaration - Define the
compareTomethod with your comparison logic
Here's the structure:
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
// Return negative if this < other
// Return zero if this == other
// Return positive if this > other
return Integer.compare(this.age, other.age);
}
}
The compareTo Contract
Your compareTo method must return:
- A negative integer if
thisobject is "less than" the other - Zero if they're considered equal
- A positive integer if
thisobject is "greater than" the other
In our example, we compare by age using Integer.compare, which handles the numeric comparison correctly (including edge cases).
Once implemented, your Person objects can now be sorted naturally—Collections.sort(personList) will sort by age automatically!
Key Takeaway: Implementing Comparable<T> with a properly defined compareTo method gives your custom class natural ordering, enabling automatic sorting and integration with Java's collection utilities.