Chinaunix首页 | 论坛 | 博客
  • 博客访问: 244818
  • 博文数量: 164
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1129
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-09 21:55
文章分类

全部博文(164)

文章存档

2017年(2)

2015年(67)

2014年(95)

我的朋友

分类: Java

2014-05-14 21:26:10



点击(此处)折叠或打开

  1. import java.util.*;

  2. /*
  3. Set:无序,不可以重复元素。
  4.     |--HashSet:数据结构是哈希表。线程是非同步的。
  5.                 保证元素唯一性的原理:判断元素的hashCode值是否相同。
  6.                 如果相同,还会继续判断元素的equals方法,是否为true。

  7.     |--TreeSet:可以对Set集合中的元素进行排序。
  8.                 底层数据结构是二叉树。
  9.                 保证元素唯一性的依据:
  10.                 compareTo方法return 0.

  11.                 TreeSet排序的第一种方式:让元素自身具备比较性。
  12.                 元素需要实现Comparable接口,覆盖compareTo方法。
  13.                 也种方式也成为元素的自然顺序,或者叫做默认顺序。

  14.                 TreeSet的第二种排序方式。
  15.                 当元素自身不具备比较性时,或者具备的比较性不是所需要的。
  16.                 这时就需要让集合自身具备比较性。
  17.                 在集合初始化时,就有了比较方式。








  18. 需求:
  19. 往TreeSet集合中存储自定义对象学生。
  20. 想按照学生的年龄进行排序。


  21. 记住,排序时,当主要条件相同时,一定判断一下次要条件。


  22. */

  23. class TreeSetDemo
  24. {
  25.     public static void main(String[] args)
  26.     {
  27.         TreeSet ts = new TreeSet();

  28.         ts.add(new Student("lisi02",22));
  29.         ts.add(new Student("lisi007",20));
  30.         ts.add(new Student("lisi09",19));
  31.         ts.add(new Student("lisi08",19));
  32.         //ts.add(new Student("lisi007",20));
  33.         //ts.add(new Student("lisi01",40));

  34.         Iterator it = ts.iterator();
  35.         while(it.hasNext())
  36.         {
  37.             Student stu = (Student)it.next();
  38.             System.out.println(stu.getName()+"..."+stu.getAge());
  39.         }
  40.     }
  41. }


  42. class Student implements Comparable//该接口强制让学生具备比较性。
  43. {
  44.     private String name;
  45.     private int age;

  46.     Student(String name,int age)
  47.     {
  48.         this.name = name;
  49.         this.age = age;
  50.     }

  51.     public int compareTo(Object obj)
  52.     {

  53.         //return 0;
  54.         
  55.         if(!(obj instanceof Student))
  56.             throw new RuntimeException("不是学生对象");
  57.         Student s = (Student)obj;

  58.         System.out.println(this.name+"....compareto....."+s.name);
  59.         if(this.age>s.age)
  60.             return 1;
  61.         if(this.age==s.age)
  62.         {
  63.             return this.name.compareTo(s.name);
  64.         }
  65.         return -1;
  66.         /**/
  67.     }

  68.     public String getName()
  69.     {
  70.         return name;

  71.     }
  72.     public int getAge()
  73.     {
  74.         return age;
  75.     }
  76. }

阅读(305) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~