Comparable Interface
The Comparable
interface in Java is used to define a natural ordering for objects of a class. This interface imposes a total ordering on the objects of each class that implements it. The natural ordering is used by various utility methods, such as Collections.sort()
and Arrays.sort()
, to sort objects.
The purpose is to allow objects of a class to be compared to each other for sorting purposes. Typically implemented by the class whose objects need to be ordered.
Definition
public interface Comparable<T> {
int compareTo(T o);
}
It contains a single method compareTo(T o)
: Compares this object with the specified object (passed in method parameter) for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Code implementing Comparable in a Custom Class with multiple attributes
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student other) {
int ageComparison = Integer.compare(this.age, other.age);
if (ageComparison != 0) {
return ageComparison;
}
return this.name.compareTo(other.name);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class ComparableMultipleAttributesExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Charlie", 18));
students.add(new Student("David", 25));
students.add(new Student("Eve", 22));
// Sort students by age, then by name
Collections.sort(students);
// Print sorted students
for (Student student : students) {
System.out.println(student);
}
}
}