Difference between java comparator Comparable interface and Comparator interface

There are two types of comparators in java, the Comparable interface and the Comparator interface.

When sorting an array of objects, the role of the comparator is very obvious. Let's first explain the Comparable interface.

Let the objects that need to be sorted implement the Comparable interface, rewrite the compareTo(T o) method in it, and define the sorting rules in it, then you can directly call or Collections.sort to sort the object array. The example is as follows:

import java.io.Serializable;

public class FinanceInfo implements Serializable,Comparable{

private static final long serialVersionUID = 1L;

private String seq;//Sequence number

private String productCode;//Product code

private String applyNo;//Application number

//Sort by order number

@Override

public int compareTo(FinanceInfo o) {

return o.getApplyNo().compareTo(this.getApplyNo());

}

}

public class ComparableDemo01 {   

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        FinanceInfo stu[]={new FinanceInfo ("zhangsan",20,90.0f),

                new FinanceInfo ("wangwu",20,99.0f),

                new FinanceInfo ("sunliu",22,100.0f)};

        Collections.sort(stu);

        for(FinanceInfo s:stu)  {

            System.out.println(s);

        }

    }

}

However, when designing a class, it is often not considered that the class implements the Comparable interface, so we need to use another comparator interface Comparator. From the above example, we can find that compareTo(T o) has only one parameter, and compare(T o1,T o2) that must be implemented in the Comparator interface has two parameters.

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+"\t\t"+age+"\t\t"+score;

    }

}

class StudentComparator implements Comparator{

    @Override

    public int compare(Student o1, Student o2) {

        // TODO Auto-generated method stub

        if(o1.getScore()>o2.getScore())

            return -1;

        else if(o1.getScore()

            return 1;

        else{

            if(o1.getAge()>o2.getAge())

                return 1;

            else if(o1.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);
        }
    }
}

Difference Between Comparable and Comparator

Comparable and Comparator are both used to compare and sort elements in a collection.

Comparable is an ordering implemented by methods defined inside the collection, under java.lang.

Comparator is a sort implemented outside the collection, under java.util>.

Comparable is an interface that an object itself already supports for self-comparison. For example, String and Integer implement the Comparable interface themselves, which can perform comparison operations. Custom classes can be sorted after being added to the list container, or they can implement the Comparable interface. If you do not specify a Comparator when sorting by the sort method of the Collections class, it will be sorted in natural order. The so-called natural order is to implement the sorting method set by the Comparable interface.

Comparator is a special comparator. When the object does not support self-comparison or the self-comparison function cannot meet the requirements, a comparator can be written to complete the size comparison between two objects. The Comparatorl class embodies a strategy design pattern that does not change the object itself, but uses a strategy object to change its behavior.

All in all, Comparable is a self-completion comparison, and a Comparator is an external program that implements the comparison.

Analysis two:

Next, I will use a summary to describe the difference between the two:

1. Comparator defines the implementation outside the collection (that is, the class you want to compare), while the Comparable interface implements the method in the class you want to compare. In this way, Comparator is more like a dedicated comparator.

2. Comparator realizes the separation of algorithm and data. It can also be seen from the code. In fact, this is complementary to the first point, because Comparable depends on a certain class that needs to be compared.

3. Comparable supports self-comparison. Self-comparison means that there is a CompareTo() method in classes such as String, which can directly compare objects of the String class. This can also be compared from the Arrays.sort() method in Comparator and Comparable. It can be seen that the form with only array parameters is more similar to the example in the book. 

4. Extending from point 3, we can see what to do when we try to rewrite the rules when we are not satisfied with self-comparison functions, such as the String class - through Comparator because it supports external comparison, it is separate.

5. When the design of one class after another is completed, perhaps we did not initially envisage the problem of class comparison, and did not use the Comparable interface, then we can use Comparator to complete it later without changing the construction of the previously completed class.

6. When using the Arrays.sort() method, note that the parameters of the two are different. Comparator has one more parameter. The second parameter is the object of the class that uses the Comparator interface and is regarded as a dedicated comparator.

The above analysis is mostly personal understanding, if there are any mistakes, I hope to correct it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325871245&siteId=291194637