黑马程序员技术交流社区

标题: TreeSet中比较器的运行流程是什么? [打印本页]

作者: 郭孟涛    时间: 2013-2-19 02:29
标题: TreeSet中比较器的运行流程是什么?
本帖最后由 郭孟涛 于 2013-2-19 02:48 编辑

请问比较的时候是怎么依次输出的一下结果?特别是第二行的 29  和 30是什么时候被赋值的?分析半天没看懂。总觉得是同时赋值的。
30   30
29   30
29   30
29   29
38   29
38   30
29   29
14   29
14   29
27   29
27   29
27   14
  1. import java.util.*;


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

  7.         ts.add(new Student("lisi0",30));
  8.         ts.add(new Student("lisixx",29));
  9.         ts.add(new Student("lisi9",29));
  10.         ts.add(new Student("lisi8",38));
  11.         ts.add(new Student("lisixx",29));
  12.         ts.add(new Student("lisi4",14));
  13.         //ts.add(new Student(39));
  14.         ts.add(new Student("lisi7",27));


  15.         System.out.println(ts);
  16.     }
  17. }

  18. //同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。
  19. class Student implements Comparable
  20. {
  21.     private int age;
  22.     private String name;
  23.     Student(String name,int age)
  24.     {
  25.         this.age = age;
  26.         this.name = name;
  27.     }

  28.     public int compareTo(Object obj)
  29.     {
  30.                
  31.         //Student stu = obj;
  32.         Student stu = (Student)obj;
  33.                 System.out.println(this.age+"   "+stu.age);//这里是什么时候被赋值?
  34.         
  35.         int num = new Integer(this.age).compareTo(new Integer(stu.age));

  36.         return num==0?this.name.compareTo(stu.name):num;

  37.         /*
  38.         if(this.age>stu.age)
  39.             return 1;
  40.         if(this.age==stu.age)
  41.             return this.name.compareTo(stu.name);
  42.         return -1;
  43.         */
  44.         /**/
  45.     }

  46.     //public int getAge()
  47.     {
  48.      //   return age;
  49.     }
  50.     public String toString()
  51.     {
  52.         return name+"::"+age;
  53.     }

  54. }
复制代码

作者: 王钊    时间: 2013-2-19 07:24
本帖最后由 王钊 于 2013-2-19 07:33 编辑

毕老师讲过,因为TreeSet内部采用的是采用的是二叉树模型。
如图:我帮你画的。你新加的元素先和第一个元素比较,如果比它大分叉向右,再依次比较,如果比它小分叉向左,再依次比较,直到找到属于自己的位置。
二叉树有效地减少了比较次数,不需要每个元素都进行比较,每次比较都缩小了一定的范围。

二叉树.png (17.2 KB, 下载次数: 17)

二叉树.png

作者: 黑马-王言龙    时间: 2013-2-19 12:10
这个30和30自己比一下,不正常,是不是新版本的BUG




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2