The Comparable interface in Java is used to define the natural ordering of objects. It allows objects of a class to be compared to each other, which is essential for sorting and ordering collections like arrays, lists, or sets. The interface is part of the java.lang package.
Interface Declaration
public interface Comparable<T> {
int compareTo(T obj);
}
- The Comparable interface imposes a total ordering on the objects of the implementing class.
- Classes that implement Comparable must override the compareTo() method.
- The compareTo() method defines the natural ordering and is used by methods like Collections.sort() or Arrays.sort().
compareTo() Method in Comparable
int compareTo(T obj)
Compares the current object with the specified object obj. Returns a negative integer, zero, or a positive integer if the current object is less than, equal to, or greater than the specified object.
Return Value of compareTo()
- Negative Value (< 0): Current object is less than the specified object.
- Zero (0): Current object is equal to the specified object.
- Positive Value (> 0): Current object is greater than the specified object.
Implementing Comparable
import java.util.*;
class Student implements Comparable<Student> {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
@Override
public int compareTo(Student other) {
return this.marks - other.marks; // ascending order by marks
}
@Override
public String toString() {
return name + ": " + marks;
}
}
public class ComparableExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 92));
students.add(new Student("Charlie", 78));
Collections.sort(students);
for (Student s : students) {
System.out.println(s);
}
}
}
Output
Charlie: 78 Alice: 85 Bob: 92
- Natural Ordering: The compareTo() method defines how objects are naturally ordered.
- Type Safety: Comparable is generic (Comparable<T>), ensuring type safety.
- Sorting Collections: Collections and arrays can be sorted using compareTo() without explicitly providing a comparator.
- Primitive-like Ordering: Numeric types, strings, and dates in Java implement Comparable by default.
Sorting Strings
import java.util.*;
public class StringSortExample {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie"};
Arrays.sort(names); // uses natural ordering (alphabetical)
System.out.println(Arrays.toString(names));
}
}
Output
[Alice, Bob, Charlie]
Advantages
- Simplifies sorting of objects in lists or arrays.
- Works seamlessly with collection utilities like Collections.sort() and Arrays.sort().
- Provides type-safe comparisons when using generics.