In Java using the comparator Compare and Comparator

Comparable and Comparator interface class are compared to known, such as Integer, double basic data types, java can compare them, and for comparing the class, the need to manually define the field compare logic used in the comparison. Comparable can be understood as an internal comparator, and the comparator Comparator is an external, substantially the following wording:

class Apple implements Comparable<Apple>{
    int id;
    double price;
public Apple(int id, double price) {
    this.id = id;
    this.price = price;
}
public int compareTo(Apple o) {
    //return Double.compare(this.getPrice(),o.getPrice());
    if (Math.abs(this.price-o.price)<0.001)
        return 0;
    else
        return (o.price-this.price)>0?1:-1;
}
@Override
public String toString() {
    return "Apple{" +
            "id=" + id +
            ", price=" + price +
            '}';
}

}```

class AESComparator implements Comparator<Apple>{


    public int compare(Apple o1, Apple o2) {
        if (Math.abs(o1.price-o2.price)<0.001)
            return 0;
        else{
            return (o1.price-o2.price)>0?1:-1;
        }
    }
}

 实现了Comparable接口的类需要实现compareTo()方法,传入一个外部参数进行比对,实现了Comparator接口的方法需要实现compare()方法,对外部传入的两个类进行比较,从而让外部方法在比较时调用。

 两者的区别是实现Comparator接口代码更加灵活,可以定义某个类的多个比较器,从而在排序时根据实际场景自由调用,而Comparable接口实现后便不能改动。

 总结:
comparator接口:真正要实现的只有compare()方法,需要单独准备出一个类来实现comparator接口,这个类将作为指定类的排序类

public int compare(Emp o1,Emp,o2){
     return o1.id - o2.id
}
这是说如果o1的id - o2的id是正数就升序,如果负数降序。如果0就剔除

> 0 ASC
<0 DESC
= 0 is repeated, is not recorded
comparable Interface



实现该类接口不需要重新创建一个排序的类,使用接口compareble接口排序,只要重写里面的compareTo()方法

 

Collections类是一个包装类,它包含有各种有关集合操作的静态方法。就像一个工具类。

Collections.sort()

sort()排序方法,根据元素的自然排序对指定列表按升序进行排序

public static <T>void sort(List<T> list,Comparator<>),根据指定比较器产生的顺序对指定列表进行排序,此列表内的所有元素都必须可使用指定的比较器相互比较

参数:list——要排序的列表
         C——确定列表顺序的比较器

Guess you like

Origin blog.51cto.com/14232658/2476722