In depth analysis of the Java comparator Comparable interface and the Comaprator interface

  • 2020-04-01 02:01:40
  • OfStack

The Java Comparator has two classes, the Comparable interface and the Comparator interface.
The comparator is very useful when sorting an array of objects, so let's start with the Comparable interface.
Having the object that needs to be sorted implement the Comparable interface and override the compareTo(T o) method in it to define the collating rule, you can directly call java.util.arrays.sort () to sort the array of objects as follows:

class Student implements Comparable<Student>{
    private String name;
    private int age;
    private float score;

    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public String toString()
    {
        return name+"tt"+age+"tt"+score;
    }
    @Override
    public int compareTo(Student o) {
        // TODO Auto-generated method stub
        if(this.score>o.score)//Score is private, why can you call it directly, because inside the Student class
            return -1;//Sort by height
        else if(this.score<o.score)
            return 1;
        else{
            if(this.age>o.age)
                return 1;//Sort from base to height
            else if(this.age<o.age)
                return -1;
            else
                return 0;
        }
    }
}
public class ComparableDemo01 {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student stu[]={new Student("zhangsan",20,90.0f),
                new Student("lisi",22,90.0f),
                new Student("wangwu",20,99.0f),
                new Student("sunliu",22,100.0f)};
        java.util.Arrays.sort(stu);
        for(Student s:stu)
        {
            System.out.println(s);
        }
    }
}

Program running results:
Sunliu 22 100.0
Wangwu 20 99.0
Zhangsan 20 90.0
Lisi 22 90.0
However, when designing a class, we often don't think about the Comparable interface for the class, so we need to use another Comparator interface, the Comparator.
From the above example, we can see that compareTo(T o) has only one parameter, while compare(T o1,T o2), which must be implemented in the Comparator interface, has two parameters.
Code example:

package edu.sjtu.ist.comutil;
import java.util.Comparator;
class Student {
    private String name;
    private int age;
    private float score;

    public Student(String name, int age, float score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public float getScore() {
        return score;
    }
    public void setScore(float score) {
        this.score = score;
    }
    public String toString()
    {
        return name+"tt"+age+"tt"+score;
    }
}
class StudentComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        if(o1.getScore()>o2.getScore())
            return -1;
        else if(o1.getScore()<o2.getScore())
            return 1;
        else{
            if(o1.getAge()>o2.getAge())
                return 1;
            else if(o1.getAge()<o2.getAge())
                return -1;
            else 
                return 0;
        }
    }

}
public class ComparableDemo02 {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student stu[]={new Student("zhangsan",20,90.0f),
                new Student("lisi",22,90.0f),
                new Student("wangwu",20,99.0f),
                new Student("sunliu",22,100.0f)};
        java.util.Arrays.sort(stu,new StudentComparator());
        for(Student s:stu)
        {
            System.out.println(s);
        }
    }
}


Related articles: