TreeSet和TreeMap排序时比较元素要求元素对象必须实现Comparable接口
Collections的sort方法比较元素有两种方法:
元素对象实现Comparable接口
实体类Dog
1 public class Dog implements Cloneable,Comparable<Dog> { 2 3 private String name; 4 private String age; 5 6 public String getName() { 7 return name; 8 } 9 public void setName(String name) { 10 this.name = name; 11 } 12 public String getAge() { 13 return age; 14 } 15 public void setAge(String age) { 16 this.age = age; 17 } 18 public Dog(String name, String age) { 19 super(); 20 this.name = name; 21 this.age = age; 22 } 23 public Dog() { 24 super(); 25 } 26 @Override 27 public String toString() { 28 return "Dog [name=" + name + ", age=" + age + "]"; 29 } 30 31 public Object clone() throws CloneNotSupportedException { 32 33 return super.clone(); 34 } 35 @Override 36 public int compareTo(Dog o) { 37 38 return this.getName().compareTo(o.getName()); 39 } 40 }
测试类
1 public class Test { 2 3 public static void main(String[] args) { 4 List<Dog> list = new ArrayList<Dog>(); 5 Dog d1 = new Dog("cac", "11"); 6 Dog d2 = new Dog("bac", "11"); 7 Dog d3 = new Dog("aac", "11"); 8 Dog d4 = new Dog("eac", "11"); 9 list.add(d1); 10 list.add(d2); 11 list.add(d3); 12 list.add(d4); 13 // MyCompare mc = new MyCompare(); 14 // Collections.sort(list,mc); 15 Collections.sort(list); 16 for (Dog dog : list) { 17 System.out.println(dog); 18 } 19 20 } 21 }
结果:
Dog [name=aac, age=11]
Dog [name=bac, age=11]
Dog [name=cac, age=11]
Dog [name=eac, age=11]
自定义比较器,Collections.sort(List list,Comparator<T> compare),创建比较器类实现接口
1 public class Test { 2 3 public static void main(String[] args) { 4 List<Dog> list = new ArrayList<Dog>(); 5 Dog d1 = new Dog("cac", "11"); 6 Dog d2 = new Dog("bac", "11"); 7 Dog d3 = new Dog("aac", "11"); 8 Dog d4 = new Dog("eac", "11"); 9 list.add(d1); 10 list.add(d2); 11 list.add(d3); 12 list.add(d4); 13 MyCompare mc = new MyCompare(); 14 Collections.sort(list,mc); 15 for (Dog dog : list) { 16 System.out.println(dog); 17 } 18 19 } 20 } 21 22 class MyCompare implements Comparator<Dog>{ 23 24 @Override 25 public int compare(Dog d1, Dog d2) { 26 String s1 = d1.getName(); 27 String s2 = d2.getName(); 28 if(s1.equals(s2)) 29 return 0; 30 else { 31 return s1.compareTo(s2); 32 } 33 } 34 35 }
结果:
Dog [name=aac, age=11]
Dog [name=bac, age=11]
Dog [name=cac, age=11]
Dog [name=eac, age=11]