A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 思考。。。 中级黑马   /  2015-7-1 18:28  /  222 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class TreeSetDemo
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 TreeSet ts = new TreeSet();

  6.                 ts.add(new Student("lisi02",22));
  7.                 ts.add(new Student("lisi007",20));
  8.                 ts.add(new Student("lisi09",19));
  9.                 ts.add(new Student("lisi08",19));
  10.                 //ts.add(new Student("lisi007",20));
  11.                 //ts.add(new Student("lisi01",40));

  12.                 Iterator it = ts.iterator();
  13.                 while(it.hasNext())
  14.                 {
  15.                         Student stu = (Student)it.next();
  16.                         System.out.println(stu.getName()+"..."+stu.getAge());
  17.                 }
  18.         }
  19. }
  20. class Student implements Comparable//该接口强制让学生具备比较性。
  21. {
  22.         private String name;
  23.         private int age;

  24.         Student(String name,int age)
  25.         {
  26.                 this.name = name;
  27.                 this.age = age;
  28.         }

  29.         public int compareTo(Object obj)
  30.         {

  31.                 //return 0;
  32.                
  33.                 if(!(obj instanceof Student))
  34.                         throw new RuntimeException("不是学生对象");
  35.                 Student s = (Student)obj;

  36.                 System.out.println(this.name+"....compareto....."+s.name);
  37.                 if(this.age>s.age)
  38.                         return 1;
  39.                 if(this.age==s.age)
  40.                 {
  41.                         return this.name.compareTo(s.name);
  42.                 }
  43.                 return -1;
  44.                 /**/
  45.         }

  46.         public String getName()
  47.         {
  48.                 return name;

  49.         }
  50.         public int getAge()
  51.         {
  52.                 return age;
  53.         }
  54. }
复制代码


请问:TreeSet保证元素的唯一性也是hashCode()和equals()方法吗?在上面的实例代码中,是优先使用compareTo(Object obj)方法来保证TreeSet的元素唯一性吗?

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马