Learn about the Comparable interface and how to implement natural ordering for objects in Java.
The Comparable interface in Java is used to define a "natural ordering" between objects of the same type. This allows collections of objects to be sorted and compared in a meaningful way.
public interface Comparable<T> { // Returns negative if this < other, zero if this == other, positive if this > other public int compareTo(T other); }
Many built-in Java classes such as String, Integer, and Date implement Comparable, allowing them to be naturally ordered.
To make your custom class comparable, you need to implement the Comparable interface and provide a compareTo method.
public class Student implements Comparable<Student> { private String name; private double gpa; public Student(String name, double gpa) { this.name = name; this.gpa = gpa; } // Getters and setters... @Override public int compareTo(Student other) { // Compare based on GPA (higher GPA comes first) if (this.gpa > other.gpa) { return -1; } else if (this.gpa < other.gpa) { return 1; } else { // If GPAs are equal, compare by name return this.name.compareTo(other.name); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Double.compare(student.gpa, gpa) == 0 && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, gpa); } }
The compareTo method must follow these rules:
Once a class implements Comparable, its instances can be:
// Creating a list of students List<Student> students = new ArrayList<>(); students.add(new Student("Alice", 3.8)); students.add(new Student("Bob", 3.5)); students.add(new Student("Charlie", 4.0)); // Sorting the list using the natural ordering (defined by compareTo) Collections.sort(students); // Now students will be sorted by GPA (highest first), then by name for (Student student : students) { System.out.println(student.getName() + ": " + student.getGpa()); }
You should implement Comparable when:
If different orderings are needed for the same class, consider using Comparator (covered in Module 4) instead of or in addition to Comparable.