Chinaunix首页 | 论坛 | 博客
  • 博客访问: 96267
  • 博文数量: 54
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-30 00:36
文章分类

全部博文(54)

文章存档

2010年(1)

2009年(52)

2008年(1)

我的朋友

分类: Java

2009-10-07 18:38:38

TreeSet是依靠TreeMap来实现的。
TreeSet是一个有序集合,TreeSet中元素将按照升序排列,缺省是按照自然顺序进行排列,意味着TreeSet中元素要实现Comparable接口。
我们可以在构造TreeSet对象时,传递实现了Comparator接口的比较器对象。
 
import java.util.*;
class TreeSetTest
{
 public static void main(String[] args)
 {
  TreeSet ts=new TreeSet(new Student.StudentComparator());
  /*ts.add("winsun");
  ts.add("weixin");
  ts.add("mybole");*/
  ts.add(new Student(2,"lisi"));
  ts.add(new Student(1,"wangwu"));
  ts.add(new Student(3,"zhangsan"));
  ts.add(new Student(3,"mybole"));
  
  Iterator it=ts.iterator();
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
 }
}
class Student implements Comparable
{
 int num;
 String name;
 static class StudentComparator implements Comparator
 {
  public int compare(Object o1,Object o2)
  {
   Student s1=(Student)o1;
   Student s2=(Student)o2;
   int result=s1.num > s2.num ? 1 : (s1.num==s2.num ? 0 : -1);
   if(result==0)
   {
    result=s1.name.compareTo(s2.name);
   }
   return result;
  }
 }
 Student(int num,String name)
 {
  this.num=num;
  this.name=name;
 }
 
 public int compareTo(Object o)
 {
  Student s=(Student)o;
  return num > s.num ? 1 : (num==s.num ? 0 : -1);
 }
 public String toString()
 {
  return num+":"+name;
 }
}
阅读(504) | 评论(0) | 转发(0) |
0

上一篇:散列表

下一篇:HashSet和TreeSet的比较

给主人留下些什么吧!~~