Java
java Advanced Interview questions
Java interview questions
Java Interview Questions
Java Tutorial
Difference between Comparable and Comparator
Comparable
and Comparator
are two Java interfaces that allow objects to be compared and sorted.
Comparable
Comparable
is a functional interface that is implemented by a class to define its natural ordering.- The
compareTo
method of theComparable
interface compares an object with another object and returns an integer indicating their relative order.
class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Person other) {
if (this.age != other.age) {
return Integer.compare(this.age, other.age);
} else {
return this.name.compareTo(other.name);
}
}
}
Comparator
Comparator
, on the other hand, is a functional interface that is used to provide custom comparison logic, separate from the class’s natural ordering. The compare
method of the Comparator
interface takes two objects and returns an integer indicating their relative order.
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
class PersonAgeComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return Integer.compare(p1.age, p2.age);
}
}
class PersonNameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
}
In summary, Comparable
is used for objects to define their natural ordering, while Comparator
is used for custom comparison logic, separate from the object’s natural ordering.