你的位置:首页 > Java教程

[Java教程]【Java学习笔记】集合框架TreeSet,Comparable,Comparator


 1 public class Person implements Comparable{ 2   private String name; 3   private int age; 4    5   public Person(){ 6     super(); 7   } 8   public Person(String name, int age) 9   {10     super();11     this.name = name;12     this.age = age;13   }14   15   16   @Override17   public int hashCode() {18     19     return name.hashCode()+age*27;20   }21   @Override22   public boolean equals(Object obj) {23     if (this == obj)24       return true;25     if (!(obj instanceof Person))26       throw new ClassCastException("类型错误");27     28     Person p = (Person) obj;29     30     return this.name.equals(p.name) && this.age == p.age;31   }32   @Override33   public String toString() {34     35     return name+":"+age;36   }37   public String getName() {38     return name;39   }40   public void setName(String name) {41     this.name = name;42   }43   public int getAge() {44     return age;45   }46   public void setAge(int age) {47     this.age = age;48   }49   @Override50   public int compareTo(Object o) {  //先按年龄排,再按姓名排51     52     Person p = (Person)o;53     54     int temp = this.age - p.age;55     56     return temp==0? this.name.compareTo(p.name):temp;57     58     59   }60   61   62 }

 

 

 1 import java.util.Comparator; 2  3 import cn.itcast.p1.bean.Person; 4  5 public class ComparatorByName implements Comparator {  //先按姓名排,再按年龄排 6  7   @Override 8   public int compare(Object o1, Object o2) { 9     Person p1 = (Person)o1;10     Person p2 = (Person)o2;11     12     int temp = p1.getName().compareTo(p2.getName());13 14     return temp==0?p1.getAge()-p2.getAge() : temp;15   }16 17 }



 

 

 1 import java.util.Iterator; 2 import java.util.TreeSet; 3  4 import cn.itcast.p1.bean.Person; 5 import cn.itcast.p5.comparator.ComparatorByName; 6  7 public class TreeSetDemo { 8  9   public static void main(String[] args) {10 //    demo1();11     TreeSet ts = new TreeSet(new ComparatorByName()); //添加 new ComparatorByName(),会出现结果一,去除的话 ,出现结果2
//Comparator 优先于 Comparable
12 13 ts.add(new Person("zhangsan",28));14 ts.add(new Person("lisi",21));15 ts.add(new Person("zhouqi",29));16 ts.add(new Person("zhaoliu",25));17 ts.add(new Person("wangwu",24));18 ts.add(new Person("lisi",21));19 ts.add(new Person("zhouqi",29));20 21 Iterator it = ts.iterator();22 23 while (it.hasNext())24 {25 Person p = (Person)it.next();26 27 System.out.println(p);28 }29 30 }31 32 public static void demo1() {33 TreeSet ts = new TreeSet();34 35 ts.add("abc");36 ts.add("zaa");37 ts.add("aa");38 ts.add("nba");39 ts.add("cba");40 41 Iterator it = ts.iterator();42 43 while (it.hasNext())44 {45 System.out.println(it.next());46 }47 }48 49 }