In Advance Java, Comparable and Comparator are used to define custom sorting logic for objects. They help Java collections like Collections.sort() and TreeSet decide how objects should be ordered.
java.util packagecompareTo(Object o)compare(Object o1, Object o2)
// Student class implementing Comparable
class Student implements Comparable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
public int compareTo(Student s) {
// Sort students by id in ascending order
return this.id - s.id;
}
}
// Comparator to sort students by name
import java.util.Comparator;
class NameComparator implements Comparator {
public int compare(Student s1, Student s2) {
// Compare student names alphabetically
return s1.name.compareTo(s2.name);
}
}
Click the buttons to see how the list changes based on logic.
idnamecompareTo()