Comparable and Comparator in java

Both of these are classic interfaces,

1. java.lang.Comparable interface: natural sorting interface

     int compareTo(Object o) abstract method

2. java.util.Comparator interface: custom sorting interface

       int compare(Object o1, Object o2)

Both Comparable and Comparator are interfaces used to compare the order of objects, using the compareTo() method in the interface .

First up is our Comparable interface.

Abstract method:
    int compareTo(Object o)
    
    Return value description:
    compare the order of this object (this) and the specified object (formal parameter o).
    If the object this is less than (<) the specified object (formal parameter o), return a negative integer
    If the object this is greater than (>) the specified object (formal parameter o), return a positive integer
    If the object this is equal to (=) the specified object (Formal parameter o), it returns 0

The method of use is: Implement the Comparable interface behind the defined class.

And override the compareto method

 After implementing this interface, you can directly use CompareTo() to compare objects:

package com.atguigu.classics;

public class Tools {
//    public void compareTwoObject(类型1 s1, 类型2 s2){
//这个类型可以接收任意对象类型,想到用Object
    public static void compareTwoObject(Object s1, Object s2){
        if(((Comparable)s1).compareTo(s2)>0){
            System.out.println("s1 > s2");
        }else if(((Comparable)s1).compareTo(s2)<0){
            System.out.println("s1 < s2");
        }else{
            System.out.println("s1 = s2");
        }
    }
    public static void sort(Object[] arr){
        for(int i=0; i<arr.length-1; i++){
            for(int j=0; j<arr.length-1-i; j++){
               if(((Comparable)arr[j]).compareTo(arr[j+1]) < 0){
                        // Student temp = arr[j];
                        Object temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }

        }
    }

//    public void printArr(类型[] arr){
    //这个类型可以接收任意对象类型,想到用Object
    public static void printArr(Object[] arr){
        for(int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

 

Then we can call our method directly in our test class:

package com.atguigu.classics;

public class TestStudent2 {
    public static void main(String[] args) {
        /*
        需求:
        (1)声明两个学生对象
        (2)对两个学生做大小比较
        例如:按照id比较大小
                */
        Student s1 = new Student(1,"张三",89,23);
        Student s2 = new Student(2,"李四",90,24);

        Tools.compareTwoObject(s1,s2);

         /*
        (3)学生对象更多了,5个,把它们放到数组中
         */
        Student[] arr = new Student[5];
        arr[0] = s1;
        arr[1] = s2;
        arr[2] = new Student(3,"王五",74,25);
        arr[3] = new Student(4,"赵四",99,20);
        arr[4] = new Student(5,"刘能",76,23);

         /*
        (4)排序,按照编号从大到小排序
         */
        Tools.sort(arr);

         /*
        (5)输出
         */
         Tools.printArr(arr);
    }
}

Classic interface:
1. java.lang.Comparable interface: natural sorting interface
        int compareTo (Object o) abstract method
    Whenever two objects in Java need to be compared in size,
    then the type of the object implements the Comparable interface.

  By designing this interface, Java normalizes the problem of comparing the sizes of all two objects.

2. java.util.Comparator interface: custom sorting interface
    int compare(Object o1, Object o2)

 

If the object has other comparison requirements, it is generally a separate class that implements the java.util.Comparator interface: custom sorting interface.
Just write the corresponding comparison rules in the int compare(Object o1, Object o2) method.

Usually the java.util.Comparator interface is not implemented directly in the Student class.
For example: the java.lang.Comparable interface is OK for the main room to be placed at home, and
     the java.util.Comparator interface is a colorful flag, which is generally independent outside.

public class StudentScoreComparator implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        //按照学生的成绩从高到低排序
        //(1)先把o1,o2的类型处理一下,向下转型
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;

        return s2.getScore() - s1.getScore();
    }
}

public class StudentAgeComparator implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        //按照学生的年龄从小到大排序
        //(1)先把o1,o2的类型处理一下,向下转型
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;

        return s1.getAge() - s2.getAge();
    }
}

public static void sort(Object[] arr, Comparator c){
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                /*
                调用Comparator接口的实现类的
                 public int compare(Object o1, Object o2) 方法
                 比较两个元素的大小。
                 c.compare(arr[j], arr[j+1]) 返回结果有3种:
                 正:arr[j] > arr[j+1]
                 负:arr[j] < arr[j+1]
                 0:arr[j] = arr[j+1]
                 */
               if(c.compare(arr[j], arr[j+1]) > 0){
                    // Student temp = arr[j];
                    Object temp = arr[j];//temp的类型跟着arr数组的类型变即可
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }

 If you compare objects later, it is very convenient to use the Comparable interface.

Guess you like

Origin blog.csdn.net/sslovly/article/details/125239066