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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郭孟涛 高级黑马   /  2013-2-19 02:29  /  1528 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 郭孟涛 于 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. }
复制代码

评分

参与人数 1黑马币 +9 收起 理由
Rancho_Gump + 9

查看全部评分

3 个回复

倒序浏览
本帖最后由 王钊 于 2013-2-19 07:33 编辑

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

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

二叉树.png
回复 使用道具 举报
这个30和30自己比一下,不正常,是不是新版本的BUG
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马