First, take a look at the differences between the two interfaces:
-
Comparable is a sort interface, often used for natural sorts; If a class implements the Comparable interface, it means that “the class supports sorting.”
-
A Comparator is a Comparator. It is used when precise control of an order is required. If we need to control the order of multiple objects of a class, we can build a “comparator of the class” to sort.
Take a look at the different implementations and functions through the code
Internal comparator Comparable main code
public class Dayimplements Comparable {
private int year;
public Day(int year) {
this.year = year;
}
/ * * *@descRewrite the compareTo function. If year is greater than 0, the current class comes after the comparison class. If year is less than 0, the current class comes before the comparison class
public int compareTo(Day otherDay) {
return year - otherDay.year;
}
@Override
public String toString(a) {
return "year=" +year;
}
public int getYear(a) {
returnyear; }}Copy the code
External comparator main code
public class AscOperation implements Comparator<Day> {
/ * * *@descThe compare function. By year, if the value of return is greater than 0, the preceding digit is in ascending order. If the value of return is less than 0, the preceding digit is in descending order
public int compare(Day day1, Day day2) {
returnday1.getYear() - day2.getYear(); }}Copy the code
The client calls the code
public class Main {
public static void main(String[] args){
List days =new ArrayList();
days.add(new Day(2018));
days.add(new Day(2017));
days.add(new Day(2019));
// Implement sorting internally
Collections.sort(days);
System.out.printf("list:%s\n",days);
// Rely on external methods for sorting
Collections.sort(days,new DescOperation());
System.out.printf("list:%s\n",days);
Collections.sort(days,new AscOperation());
System.out.printf("list:%s\n",days); }}Copy the code
The specific project code can be seen on my Github address
github