Java Collections.sort()实现List排序的默认方法和自定义方法

1、第一种是model类实现Comparable接口,重写重写int compareTo(Object o)方法



public class StudentDTO implements Comparable{
 private String name;
 private int age;
public String getName(){
 return name;
}
public void setName(String name){
  this.name = name;
}
public ObjType getType(){
 return type;
}
public void setAge(int age){
  this.age= age;
}
@Override
public int compareTo(Object o){
  StudentDTO sdto = (StudentDTO)o;
  int otherAge = sdto.getAge();
  // note: enum-type's comparation depend on types' list order of enum method
  // so, if compared property is enum-type ,then its comparationfollow ObjEnum.objType order
  return this.age.compareTo(otherAge);
}
}
   主方法:   
public static void main(String[] args)
{
  List studentList = new ArrayList();
  StudentDTO s1 = new StudentDTO ();
  s.setName("yuanyuan");
  s.setAge(22);
  studentList.add(s1);
  StudentDTO s1 = new StudentDTO ();
  s.setName("lily");
  s.setAge(23);
  studentList.add(s2);
  Collections.sort(studentList); //按照age升序 22,23,
  Collections.reverse(studentList); //按照age降序 23,22 
}

2、比较器类实现Comparator接口,重写int compare(Object o1, Object o2)方法

public class StudentDTO implements Comparable{
  private String name;
  private int age;
  public String getName(){
   return name;
  }
  public void setName(String name){
   this.name = name;
  }
  public ObjType getType(){
   return type;
  }
  public void setAge(int age){
   this.age= age;
  }
} 
   比较器类:
class MyCompartor implements Comparator{
  @Override
  public int compare(Object o1, Object o2){
   StudentDTO sdto1= (StudentDTO )o1;
   StudentDTO sdto2= (StudentDTO )o2;
   return sdto1.getAge.compareTo(stdo2.getAge())
 }
}
   主方法:
public static void main(String[] args){
  List studentList = new ArrayList();
  StudentDTO s1 = new StudentDTO ();
  s.setName("yuanyuan");
  s.setAge(22);
  studentList.add(s1);
  StudentDTO s1 = new StudentDTO ();
  s.setName("lily");
  s.setAge(23);
  studentList.add(s2);
  MyComparetor mc = new MyComparetor();
  Collections.sort(studentList,mc);  //按照age升序 22,23,
  Collections.reverse(studentList,mc); //按照age降序 23,22 
}

你可能感兴趣的:(JDK源码)