This article has been included in my collection of articles: gitee.com/mydb/interv…
Comparable and Comparator are both used to sort elements in the Java language, but they are fundamentally different. They are also common interview questions, so today we are going to try them out.
1. The literal meaning is different
Comparable is the Chinese word for “to compare” and Comparable is the Chinese word for “Comparator”. Comparable ends in -able, indicating that it has a certain ability, while Comparator ends in -or, indicating that it is a participant in the comparison. This is to understand the difference literally.
2. Different usage
Both are top-level interfaces, but they have different methods and usages. Let’s look at them separately.
2.1 Comparable,
The Comparable interface has only one method, compareTo. Implementing the Comparable interface and rewriting the compareTo method will allow you to sort a class that supports collections.sort and arrays.sort.
When we were not using Comparable, the execution of the program looked like this:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
public class ComparableExample {
public static void main(String[] args) {
// Create an object
Person p1 = new Person(1.18."Java");
Person p2 = new Person(2.22."MySQL");
Person p3 = new Person(3.6."Redis");
// Add to collection
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
// Prints the collection information
list.forEach(p -> System.out.println(p.getName() +
":"+ p.getAge())); }}// The following set/get/toString annotations are provided by Lombok
@Getter
@Setter
@ToString
class Person {
private int id;
private int age;
private String name;
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name; }}Copy the code
The execution result of the program is as follows:As you can see from the figure above, when the custom class Person does not implement Comparable, the List collection is not sorted and can only be output in the order in which the elements are inserted.
Comparable (Comparable, Comparable, Comparable, Comparable, Comparable, Comparable, Comparable, Comparable, Comparable, Comparable, Comparable)
We use Comparable to implement the Comparable interface in the class of a custom object and rewrite the compareTo method to implement a custom sort as follows:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableExample {
public static void main(String[] args) {
// Create an object
Person p1 = new Person(1.18."Java");
Person p2 = new Person(2.22."MySQL");
Person p3 = new Person(3.6."Redis");
// Add objects to the collection
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
// Sort (according to the collation rules defined in compareTo in the Person class)
Collections.sort(list);
// The order in the output collection
list.forEach(p -> System.out.println(p.getName() +
":"+ p.getAge())); }}// The following set/get/toString implementations use lombok annotations
@Getter
@Setter
@ToString
static class Person implements Comparable<Person> {
private int id;
private int age;
private String name;
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public int compareTo(Person p) {
return p.getAge() - this.getAge(); }}Copy the code
The execution result of the program is as follows:
CompareTo sorting method description
The compareTo method takes p as the object to be compared, collates the current object with the object to be compared, and returns a value of type int. The order from smallest to largest is: subtract the value of the object to be compared from the current value of the object; Reverse ordering from largest to smallest does the opposite: subtract the value of the current object from the value of the compared object.
Note: If a custom object does not implement the Comparable interface, it cannot be sorted using the collections.sort method and the compiler will display the following error:
2.2 Comparator
Comparable is compareTo and Comparable is compareTo. Comparable is compareTo. Compare is Comparable.
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
public static void main(String[] args) {
// Create an object
Person p1 = new Person(1.18."Java");
Person p2 = new Person(2.22."MySQL");
Person p3 = new Person(3.6."Redis");
// Add objects to the collection
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
// Perform the sort operation (according to the collation rules defined in the PersonComparator)
Collections.sort(list, new PersonComparator());
// The order in the output collection
list.forEach(p -> System.out.println(p.getName() +
":"+ p.getAge())); }}/** * the comparator for the Person class */
class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
returnp2.getAge() - p1.getAge(); }}@Getter
@Setter
class Person {
private int id;
private int age;
private String name;
public Person(int id, int age, String name) {
this.id = id;
this.age = age; }}Copy the code
The execution result of the program is as follows:
Extension: Comparator anonymous class
In addition to creating a custom Comparator, the Comparator can also complete the function of custom Comparator more quickly and conveniently by means of anonymous classes. The specific code is as follows:
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
public static void main(String[] args) {
// Build and add data
List<Person> list = new ArrayList<>();
list.add(new Person(1.18."Java"));
list.add(new Person(2.20."MySQL"));
list.add(new Person(3.6."Redis"));
// Sort using the Comparator anonymous class
list.sort(new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
returnp2.getAge() - p1.getAge(); }});// Print the collection data
list.forEach(p -> System.out.println(p.getName() +
":"+ p.getAge())); }}@Getter
@Setter
static class Person {
private int id;
private int age;
private String name;
public Person(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name; }}Copy the code
The execution result of the program is as follows:
3. Use different scenarios
We can see from the implementation code above that using Comparable requires you to modify the existing class, that is, to sort that class, you implement the Comparable interface in that class and rewrite the compareTo method, So Comparable is more like an interface for sorting “internally.”
The use of the Comparator is different. There is no need to modify the original class for the Comparator. In the extreme case, the Person class can be sorted by creating a new custom Comparator, even if the Person class is provided by a third party. That is, the Comparator interface decoupled the original class and implemented sorting without modifying the original class. Therefore, the Comparator can be considered as an “external” sorting interface.
conclusion
Comparable and Comparator are both used to sort elements. The differences between them are as follows:
- Comparable means “to compare” and Comparator means “to compare”;
- Comparable implements sorting by overriding the compareTo method, whereas Comparator implements sorting by overriding the compare method;
- Comparable must be implemented internally by the custom class, whereas Comparator is externally defined and implemented.
Comparable is an “internal” sorting interface, whereas Comparator is an “external” sorting interface.
Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.
Blogger introduction: programmer after 80, writing blog this matter “insist” for 12 years, hobbies: reading, jogging, badminton.
My public number: Java interview analysis