Junior
What is the purpose of the Comparable interface in Java?
sobes.tech AI
Answer from AI
The Comparable interface is used to define the natural ordering of objects of a class. Classes that implement this interface can be sorted without explicitly specifying a comparator.
The compareTo(T o) method:
- Returns a negative integer if the current object is less than the specified object.
- Returns a positive integer if the current object is greater than the specified object.
- Returns zero if the objects are equal.
Example implementation:
public class MyClass implements Comparable<MyClass> {
private int value;
public MyClass(int value) {
this.value = value;
}
@Override
public int compareTo(MyClass other) {
// Comparison based on the value field
return Integer.compare(this.value, other.value);
}
// Getters, setters, equals, hashCode, etc.
}
Using with collections:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortingExample {
public static void main(String[] args) {
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(5));
list.add(new MyClass(2));
list.add(new MyClass(8));
// Sorting using the natural order
Collections.sort(list);
// Now the objects in the list are sorted in ascending order of value
for (MyClass obj : list) {
System.out.println(obj.value);
}
}
}