Comparator and Comparable compared with usage

First look at the respective general difference between the two interfaces:

  1. Comparable is ordering interfaces, commonly used in the natural order; if a class implements the Comparable interface, it means "This class supports sorting."

  2. Comparator comparator is commonly used in order if necessary to be precisely controlled; if we need to control a plurality of objects of a class of order, can create a "class Comparator" to sort.

Code to look through them to achieve the effect of different

The main code comparable internal comparator


public class Dayimplements Comparable {

    private int year;

    public Day(int year) {

        this.year = year;

    }

    /**

        * @desc 重写compareTo函数。通过year来比较,如果return 的大于0 则当前类排在比较类的后面

    * 如果return 的小于0 则当前类排在比较类的前面

    */

        public int compareTo(Day otherDay) {

            return year - otherDay.year;

        }

    @Override

    public String toString() {

        return "year=" +year;

    }

    public int getYear() {

        return year;

    }

}

复制代码

Outside the main code comparator comparator


public class AscOperation implements Comparator<Day> {

    /**

         * @desc compare函数。通过year来比较,如果return 的大于0 则前一位排在后一位的后面

        * 为升序,如果return 的小于0 则前一位排在后一位的的前面,为降序

    */

        public int compare(Day day1, Day day2) {

            return day1.getYear() - day2.getYear();

        }

}

复制代码

The client calling 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));

        //内部实现排序

        Collections.sort(days);

        System.out.printf("list:%s\n",days);

        //依靠外部方法实现排序

        Collections.sort(days,new DescOperation());

        System.out.printf("list:%s\n",days);

        Collections.sort(days,new AscOperation());

        System.out.printf("list:%s\n",days);

    }

}

复制代码

Specific project code can be seen to address my github

github

Guess you like

Origin juejin.im/post/5d6a0673f265da03ef7a2998