Comparable: Implementation Example
In Java, the Comparable interface is used to define the natural ordering of objects.
We will cover:
1. Class Declaration
2. compareTo Logic
3. Usage Example
1. Class Declaration
To implement Comparable, a class must:
- Implement the Comparable<T> interface
- Override the compareTo(T o) method
Example:
class Student implements Comparable<Student> {
int rollNo;
String name;
Student(int rollNo, String name) {
[Link] = rollNo;
[Link] = name;
}
2. compareTo Logic
The compareTo method defines how objects are compared.
Example:
@Override
public int compareTo(Student s) {
return [Link] - [Link]; // ascending order
Return values:
- Negative: this < s
- Zero: this == s
- Positive: this > s
3. Usage Example
Usage in sorting:
List<Student> list = new ArrayList<>();
[Link](new Student(2, "Alice"));
[Link](new Student(1, "Bob"));
[Link](list);
for (Student s : list) {
[Link]([Link] + " " + [Link]);