Java自定义排序
参考:https://www.cnblogs.com/huangjinyong/p/9037588.html
java集合的工具类Collections中提供了两种排序的方法,分别是:
- Collections.sort(List list)
- Collections.sort(List list,Comparator c)
第一种称为自然排序,参与排序的对象需实现comparable接口,重写其compareTo()方法,方法体中实现对象的比较大小规则,示例如下:
实体类:(基本属性,getter/setter方法,有参无参构造方法,toString方法)
1 package test; 2 3 public class Emp implements Comparable { 4 5 private String name; 6 private int age; 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 public Emp() { 20 super(); 21 } 22 public Emp(String name, int age) { 23 super(); 24 this.name = name; 25 this.age = age; 26 } 27 @Override 28 public String toString() { 29 return "Emp [name=" + name + ", age=" + age + "]"; 30 } 31 @Override 32 public int compareTo(Object o) { 33 if(o instanceof Emp){//判断是否可以转换,不能则抛出异常 34 Emp emp = (Emp) o; 35 // return this.age-emp.getAge();//按照年龄升序排序 36 return this.name.compareTo(emp.getName());//换姓名升序排序 37 } 38 throw new ClassCastException("不能转换为Emp类型的对象..."); 39 } 40 41 }
显然这种方法限制较多,一般用第二种匿名内部类
1 Collections.sort(ans,new Comparator(){ 2 @Override 3 public int compare(Object a1, Object b1){ 4 if(a1 instanceof ArrayList && b1 instanceof ArrayList) { 5 ArrayList<TreeNode> a = (ArrayList<TreeNode>) a1; 6 ArrayList<TreeNode> b = (ArrayList<TreeNode>) b1; 7 8 if (a.size() > b.size()) return -1; 9 else if (a.size() == b.size()) return 0; 10 else return 1; 11 } 12 throw new ClassCastException("不能转换为ArrayList类型"); 13 } 14 });