Comparator与Comparable比较

2018-09-02  本文已影响40人  PC_Repair

Comparator和Comparable比较:

参数 Comparable Comparator
排序逻辑 排序逻辑必须在待排序对象的类中,故称之为自然排序 排序逻辑在另一个实现
实现 实现Comparable接口 实现Comparator接口
排序方法 int compareTo(Object o1) int compare(Object o1,Object o2)
触发排序 Collections.sort(List) Collections.sort(List, Comparator)
接口所在包 java.lang.Comparable java.util.Comparator
Comparable接口:
public class Person  implements Comparable {
    private String name;
    private Integer age;
    private String mind;
    //省略getter 和 setter方法、构造函数、toString函数
    @Override
    public int compareTo(Object o) {
        Person targetPerson = (Person)o;
        int ret = this.name.compareTo(targetPerson.getName());
        if(ret == 0){
            return Integer.compare(this.age,targetPerson.getAge());
        }
        if(ret == 0){
            return this.getMind().compareTo(targetPerson.getMind());
        }
        return ret;
    }
}
Comparator接口:
public class PersonComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        //使用到了Person类中的compareTo方法进行比较
        //若Person没实现Comparable接口,也可以自行比较
        int ret = p1.getName().compareTo(p2.getName());
        if(ret == 0){
            return p1.getAge().compareTo(p2.getAge());
        }
        return ret;
    }
}

测试比较:

public class Test {
    public static void main(String[] args){
        //生成数据
        List<Person> personList1 = generatePersonList();
        List<Person> personList2 = generatePersonList();
        //排序一:
        Collections.sort(personList1);
        print("Collections.sort(list)",personList1);
        //排序二
        PersonComparator pc = new PersonComparator();
        //PersonComparator2 pc2 = new PersonComparator2();
        Collections.sort(personList2,pc.thenComparing(pc));
        print("thenComparing",personList2);
    }

    //生成待排序数组
    private static List<Person> generatePersonList() {
        List<Person> retList = new ArrayList<>(16);
        retList.addAll(
                Arrays.asList(
                        new Person[]{
                                new Person("erMaZi", 19, "good"),
                                new Person("wangWu", 18, "middle"),
                                new Person("liSi", 17, "bad"),
                                new Person("wangWu", 16, "middla"),
                        }
                )
        );
        return retList;
    }
    public static void print(String message,List<Person> personList){
        System.out.println(message+":");
        for(Person p:personList){
            System.out.println(p);
        }
        System.out.println();
    }
}
jdk官方默认排序:
< return -1
= return 0
> return 1
< return 1
= return 0
> return -1
上一篇 下一篇

猜你喜欢

热点阅读