Collections.sort()方法对象排序

 
  
Collections.sort()方法可以对List对象进行排序,用户需要按特定属性进行排序,有两种实现方法:
1. public static Comparable> void sort(List list)
使用Collection的这个方法,需要T类的对象实现Comparable接口,如下:


class Employee implements Comparable{
    private Integer pay;


    public Employee(int pay){
        this.pay=pay;
    }


     public void show(){
         System.out.println(pay);
     }

     @Override
     public int compareTo(Employee o) {
         return this.pay.compareTo(o.pay);
     }
}

    测试一下:

public class Test{
    public static void main(String[] args) {
      List list=new ArrayList();
      list.add(new Employee(22));
      list.add(new Employee(1));
      list.add(new Employee(233));
      list.add(new Employee(12));
      list.add(new Employee(165));

      Collection.sort(list);
      for(Employee e:list){
          e.show();
      }

}

    输出结果如下
    1
    12
    22
    165
    233
2.public static void sort( List  list, Comparator  c) 

class Employer{
     private Integer age;
     public Employer(int age) {
         this.age=age;
     }
    public void show(){
         System.out.println(age);
    }
    public Integer getAge(){
         return this.age;
    }
}
    测试一下

public class Test{

    public static void main(String[] args) {
      List list=new ArrayList();
      list.add(new Employer(22));
      list.add(new Employer(1));
      list.add(new Employer(233));
      list.add(new Employer(12));
      list.add(new Employer(165));
      Collections.sort(list,new Comparator() {
          @Override
          public int compare(Employer o1, Employer o2) {
              return o1.getAge().compareTo(o2.getAge());
          }
      });
      for(Employer e:list){
          e.show();
      
}

    }

}

    1
    12
    22
    165
    233
总结:第一种方法只能按固定属性排序,后者比较灵活,但是代码稍显复杂。

你可能感兴趣的:(Collections.sort()方法对象排序)