Java internal interface ordering and external interface ordering

Java's Comparable interface (internal sorting interface) and Comparator interface (external sorting interface)

Comparable interface

Comparable: "Comparable", (the element class corresponding to the object to be compared needs to implement the Comparable interface)
When using this strategy to compare, two objects (here two objects refer to two different instances of a class) themselves It must be "comparable." The comparison criterion is defined by the class of the object . This comparable ability is inherent in the object itself, so the comparison can be completed without the participation of a third party. To make the two objects themselves comparable, the class in which the object is located must implement the Comparable interface. Its compareTo() method only needs one parameter, because there is only the relationship between "you" and "me", and there is no third party.
For example, two people have to compare their heights. It is an inherent ability of humans to distinguish between heights. As long as two people stand together, they can tell which one is tall and which is short.

Comparable defines that the
Comparable interface only includes one function, and its definition is as follows:

public interface Comparable<T> {
    
       
 public int compareTo(T o); 
 }

Regarding the return value: It
can be seen that the compareTo method returns an int value, which has three return values:

  1. Return a negative number: indicates that the current object is smaller than the comparison object
  2. Return 0: Indicates that the current object is equal to the target object
  3. Returns a positive number: indicates that the current object is larger than the target object

Comparator interface

Comparator: When the "comparator"
uses this strategy to compare, how to compare has nothing to do with the two objects themselves, but is done by a third party (ie, the comparator). The third-party comparator class needs to be specially designed: as long as it implements the Comparator interface, any class (object) may become a "comparator", but the comparator does not compare its own instances, but compares two different objects of other classes , The comparator acts as an "arbitrator" here, which is why the compare() method requires two parameters.
For example, if two people want to compare who has a higher IQ, they cannot do it on their own. At this time, a comparator (for example, IQ test questions) is needed.

Note: The two interfaces of Comparable and Comparator have nothing to do with the collection interface (Collection)** itself, but are usually related to the elements in the collection, because the sorting of the collection uses the methods in these two sorting interfaces (choose the other One). If multiple instances of a class want to be sorted, they must implement Comparable or provide the corresponding Comparator before they can be sorted using Collections.sort().

Here we need to specifically explain: java.util.Collections does not belong to the Java collection framework. It is a collection tool class , which contains static methods for special operations on collections, such as sorting, copying, matching search, etc. And so on, for example, we often use its sorting methods: Collections.sort(List), Collections.sort(List, Comparator) .

Comparator defines the
Comparator interface only includes two functions, its definition is as follows:

package java.util;
public interface Comparator<T> {
    
    
      int compare(T o1, T o2);
      boolean equals(Object obj);
       }

int compare(T o1, T o2) is "compare the size of o1 and o2".

  1. Return "negative number", meaning "o1 is smaller than o2";
  2. Return "zero", meaning "o1 is equal to o2";
  3. Return "positive number", meaning "o1 is greater than o2".

Comparator and Comparable comparison:

The so-called inner and outer sorting are relative to the class. Comparable is a sorting interface; if a class implements the Comparable interface, it means "the class supports sorting". Comparator is a comparator; if you need to control the order of a certain class, you can create a "comparator of this class" to sort.

Comparable is equivalent to "internal comparator", and Comparator is equivalent to "external comparator".

Code example

1. We create a CSVData class, this class is used to save student information, the source of the information is a.csv file

package 排序接口;

import java.util.Comparator;

public class CsvData implements Comparable<CsvData>{
    
    

    //生成表格的变量及其Getter、Setter
    private String number;
    private String name;
    private String math;
    private String chinese;
    private String chemistry;
    private String english;
    private String Geography;
    private String history;
    private String physics;
    private String sum;
    private String average;

    public void setNumber(String number) {
    
    
        this.number = number;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public void setMath(String math) {
    
    
        this.math = math;
    }

    public void setChinese(String chinese) {
    
    
        this.chinese = chinese;
    }

    public void setChemistry(String chemistry) {
    
    
        this.chemistry = chemistry;
    }

    public void setEnglish(String english) {
    
    
        this.english = english;
    }

    public void setGeography(String geography) {
    
    
        Geography = geography;
    }

    public void setHistory(String history) {
    
    
        this.history = history;
    }

    public void setPhysics(String physics) {
    
    
        this.physics = physics;
    }

    public void setSum(String sum) {
    
    
        this.sum = sum;
    }

    public void setAverage(String average) {
    
    
        this.average = average;
    }

    public String getNumber() {
    
    
        return number;
    }

    public String getName() {
    
    
        return name;
    }

    public String getMath() {
    
    
        return math;
    }

    public String getChinese() {
    
    
        return chinese;
    }

    public String getChemistry() {
    
    
        return chemistry;
    }

    public String getEnglish() {
    
    
        return english;
    }

    public String getGeography() {
    
    
        return Geography;
    }

    public String getHistory() {
    
    
        return history;
    }

    public String getPhysics() {
    
    
        return physics;
    }

    public String getSum() {
    
    
        return sum;
    }

    public String getAverage() {
    
    
        return average;
    }

    public String getmessage(){
    
    
        return(number + "\t" + name + "\t" + math + "\t" + chinese + "\t" + chemistry + "\t" + english
                + "\t" + Geography + "\t" + history + "\t" + physics + "\t" + sum + "\t" + average);
    }

    public int compareTo(CsvData s) {
    
    
        //升序   Comparable
        int num = Integer.parseInt(this.sum)-Integer.parseInt(s.sum);
        //如果分数相同就比较名字
        return num==0 ? this.name.compareTo(s.name): num;
    }
}

Test category:

package 排序接口;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class test {
    
    
    public static void main(String[] args) {
    
    

        System.out.println("********************排序前*********************");
        System.out.println("学号  姓名  数学 语文 化学 英语 地理 历史 物理 总分 平均分");
        LinkedList<CsvData> listRead;
        //读入数据
        listRead = CSVio.readCSV("E://a.csv");
        //取前20个数据
        List<CsvData> listRead1 = listRead.subList(0,20);
        for (int i = 0 ; i < listRead1.size(); i++ )
        System.out.println(listRead1.get(i).getmessage());

        System.out.println("************Comparable list排序(升序,可以重复的)*****************");
        System.out.println("学号  姓名  数学 语文 化学 英语 地理 历史 物理 总分 平均分");
        Collections.sort(listRead1);//Comparable list 排序
        for(CsvData s:listRead1){
    
    
            System.out.println(s.getmessage());
        }

        Collections.sort(listRead1, new Comparator<CsvData>() {
    
    //内部类  Comparator
            @Override
            public int compare(CsvData o1, CsvData o2) {
    
    //降序
                return Integer.parseInt(o2.getSum()) - Integer.parseInt(o1.getSum());
            }
        });

        System.out.println("*************Comparator list 排序(降序,可以重复的)*****************");
        System.out.println("学号  姓名  数学 语文 化学 英语 地理 历史 物理 总分 平均分");
        for(CsvData s:listRead1){
    
    
            System.out.println(s.getmessage());
        }
    }
}

At this time, you need to use the Collections.sort() method .

Now, you need to retrieve all the information and display them in a certain order (such as increasing by grade) . There are two strategies for Collections.sort(): one is to make the class of the elements in the collection implement the Comparable interface, and the other is Use the comparator provided by the user (ie Comparator).

But in practical applications, you can use the compareTo() method of Comparable to define the default sorting method, and use the Comparator to define other sorting methods.

Summary-Comparison of Camparable interface and Comparator interface

1. The usage of Camparable is: define and implement compareTo() method inside the class to be compared, and then use Collections. sort() to realize sorting, and Comparator is the sorting realized outside the class to be compared. Therefore, if you want to implement sorting, you need to implement the compareTo() method of the Comparable interface within the class or define the method compare() that implements the Comparator interface outside the class.
Comparable is an object that already supports the interface that needs to be implemented for self-comparison (such as String, Integer can complete the comparison operation by itself), and Comparator is a dedicated comparator, when the object does not support self-comparison or the self-comparison function cannot When meeting your requirements, you can write a comparator to compare the size of two objects.
2. A class that implements the Camparable interface indicates that objects of this class can be compared with each other, and the collection of objects of this class can be sorted directly using the sort() method. Generally, the beans we write must implement this interface, which is also the specification of standard javabeans.
3. Comparator can be regarded as the realization of an algorithm, which separates the algorithm and data. Comparator can also be used in the following two scenarios:
1) The designer of the class did not consider the comparison problem and did not implement the Camparable interface. We can use the Comparator to Achieve sorting without having to change the class itself. For example, you use a third-party class, but the third-party class does not implement the Camparable interface, and you cannot change its code. In addition, once the class is written, it is not allowed to be modified, but it can be extended. You can only use Comparator to achieve sorting.

2) Multiple sorting criteria can be used, such as ascending order, descending order, etc.
For example, the implementation of Comparable can only define one comparison method, compareTo(), but sometimes a different sorting method will be performed on a collection. At this time, other various Comparators can be provided to sort the collection, and for the sorting The elements do not need to be changed, so I think Comparator provides more flexibility.

The class of imported data, the target data file is csv

package 排序接口;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class CSVio {
    
    
    /**
     * 读取 CSV 文件
     *
     * @return
     */
    public static LinkedList<CsvData> readCSV(String path) {
    
    
        LinkedList<CsvData> list = new LinkedList<>();
        BufferedReader reader = null;
        try {
    
    
            FileInputStream fis = new FileInputStream(path);
            InputStreamReader isr = new InputStreamReader(fis, "GBK");
            reader = new BufferedReader(isr);
            String line;
            while ((line = reader.readLine()) != null) {
    
    
                String[] rows = line.split(",");
                CsvData info = new CsvData();
                info.setNumber(rows.length > 0 ? rows[0] : null);
                info.setName(rows.length > 1 ? rows[1] : null);
                info.setMath(rows.length > 2 ? rows[2] : null);
                info.setChinese(rows.length > 3 ? rows[3] : null);
                info.setChemistry(rows.length > 4 ? rows[4] : null);
                info.setEnglish(rows.length > 5 ? rows[5] : null);
                info.setGeography(rows.length > 6 ? rows[6] : null);
                info.setHistory(rows.length > 7 ? rows[7] : null);
                info.setPhysics(rows.length > 8 ? rows[8] : null);
                info.setSum(rows.length > 9 ? rows[9] : null);
                info.setAverage(rows.length > 10 ? rows[10] : null);
                list.add(info);
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (reader != null) {
    
    
                try {
    
    
                    reader.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        if (!list.isEmpty()) {
    
    
            // 移除 CSV 首行标题
            list.remove(0);
        }
        return list;
    }

    /**
     * 写入 CSV 文件
     *
     * @return
     */
    public static void writeCsv(List<CsvData> dataList, String filePath) {
    
    
        CsvData header = new CsvData();
        //设置表头
        dataList.add(0, header);
        try {
    
    
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
            BufferedWriter bw = new BufferedWriter(osw);
            for (CsvData data : dataList) {
    
    
                String line = data.getNumber() + ","
                        + data.getName() + ","
                        + data.getMath() + ","
                        + data.getChinese() + ","
                        + data.getEnglish();
                //等等
                bw.write(line + "\t\n");
            }
            bw.close();
            osw.close();
            fos.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

}

Learn to cite references:

https://blog.csdn.net/zolalad/article/details/30060499

https://www.cnblogs.com/cikai/p/13632000.html

Guess you like

Origin blog.csdn.net/weixin_44529429/article/details/112209452