集合進行排序的兩種方式

目錄

方法1:實現comparable接口

方法2:自定義排序(Comparator接口、compare方法)


參考:https://www.cnblogs.com/huangjinyong/p/9037588.html

java集合的工具類Collections中提供了兩種排序的方法,分別是:

  1. Collections.sort(List list)
  2. Collections.sort(List list,Comparator c)

方法1:實現comparable接口

參與排序的對象需實現comparable接口,重寫其compareTo()方法,方法體中實現對象的比較大小規則,示例如下: 

package test;

public class Emp implements Comparable {

    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Emp() {
        super();
    }
    public Emp(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Emp [name=" + name + ", age=" + age + "]";
    }
    @Override
    public int compareTo(Object o) {
        if(o instanceof Emp){
            Emp emp = (Emp) o;
//          return this.age-emp.getAge();//按照年齡升序排序
            return this.name.compareTo(emp.getName());//換姓名升序排序
        }
        throw new ClassCastException("不能轉換爲Emp類型的對象...");
    }

}

方法2:自定義排序(Comparator接口、compare方法)

先new一個Comparator接口的比較器對象c,同時實現compare()其方法;然後將比較器對象c傳給Collections.sort()方法的參數列表中,實現排序功能;

/**使用Comparator比較器按age升序排序*/
    @Test
    public void testComparatorSortAge(){
        Collections.sort(list,new Comparator () {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Emp && o2 instanceof Emp){
                    Emp e1 = (Emp) o1;
                    Emp e2 = (Emp) o2;
                    return e1.getAge() - e2.getAge();
                }
                throw new ClassCastException("不能轉換爲Emp類型");
            }
        });
        System.out.println("使用Comparator比較器按age升序排序後:");
        for(Object o : list){
            System.out.println(o);
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章