1 package cn.itcast.p5.treeset.demo; 2 3 import java.util.Iterator; 4 import java.util.TreeSet; 5 6 import cn.itcast.p.bean.Person; 7 8 public class TreeSetDemo { 9 10 public static void main(String[] args) { 11 // TODO Auto-generated method stub 12 // demo1(); 13 TreeSet ts = new TreeSet(/*new ComparatorByName()*/);//比较器排序优先于person的自然排序,实际开发比较器常用,person一般会实现comparator接口 14 /* 15 * 以Person对象的年龄进行从小到大的排序。 16 * 17 */ 18 ts.add(new Person("zhangsan",28)); 19 ts.add(new Person("wangwu",29)); 20 ts.add(new Person("lisi",21)); 21 ts.add(new Person("zhouqi",29)); 22 ts.add(new Person("zhaoliu",25));//Person cannot be cast to class java.lang.Comparable 23 24 Iterator it = ts.iterator(); 25 26 while(it.hasNext()) { 27 Person p = (Person)it.next(); 28 29 System.out.println(p.getName()+":"+p.getAge()); 30 } 31 } 32 33 34 35 /** 36 * 37 */ 38 public static void demo1() { 39 TreeSet ts = new TreeSet(); 40 41 ts.add("abc"); 42 ts.add("zaa"); 43 ts.add("aa"); 44 ts.add("nba"); 45 ts.add("cba"); 46 47 Iterator it = ts.iterator(); 48 49 while(it.hasNext()) { 50 System.out.println(it.next()); 51 } 52 } 53 54 }
1 package cn.itcast.p.bean; 2 3 public class Person /*treeset用*/implements Comparable { 4 private String name; 5 private int age; 6 7 8 public Person() { 9 super(); 10 // TODO Auto-generated constructor stub 11 } 12 public Person(String name, int age) { 13 super(); 14 this.name = name; 15 this.age = age; 16 17 } 18 19 @Override 20 public int hashCode() { 21 System.out.println(this+".....hashCode"); 22 // TODO Auto-generated method stub 23 return name.hashCode()+age*27;//age后面乘以一个数增大离散程度,减少返回哈希值相等的几率 24 //好比张三哈希值20 年龄40 李四哈希值30,年龄30 结果哈希值一样 25 //乘一个数后就不一样了离散程度变大了 26 27 28 //return 100;//会比较equals 29 } 30 public boolean equals(Object obj) { 31 //健壮性 32 if (this == obj) {//有可能传入相同的对象,可以先行判断是否为同一对象add(p) add(p)这种传入两次 33 return true; 34 } 35 if (!(obj instanceof Person)) {//判断是否为Person类型,类型不一致也不应该传入 36 throw new ClassCastException("类型错误"); 37 } 38 39 // System.out.println(this+"...equals...."+obj); 40 Person p = (Person)obj; 41 42 43 return this.name.equals(p.name) && this.age == p.age; 44 } 45 public String getName() { 46 return name; 47 } 48 public void setName(String name) { 49 this.name = name; 50 } 51 public int getAge() { 52 return age; 53 } 54 public void setAge(int age) { 55 this.age = age; 56 } 57 //ctrl+alt+s 快捷构造set,get方法 初始化等 58 public String toString() { 59 return name+":"+age; 60 } 61 @Override 62 public int compareTo(Object o) {//对象的自然排序(treeset) 63 // TODO Auto-generated method stub 64 Person p = (Person)o; 65 int temp = this.age - p.age; 66 return temp==0?this.name.compareTo(p.name):temp;//主要条件次要条件,以年龄 67 68 // int temp = this.name.compareTo(p.name); 69 // return temp==0?this.age-p.age:temp;//以名字为主要条件 70 /* 71 * if (this.age>p.age) 72 * return 1; 73 * 74 * if (this.age<p.age) 75 * return -1; 76 * if (this.age == p.age) { 77 * return this.name.compareTo(p.name); 78 * } 79 */ 80 81 } 82 }
见集合框架TXT