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

全部博文(164)

文章存档

2017年(2)

2015年(67)

2014年(95)

我的朋友

分类: Java

2014-05-14 21:28:58



点击(此处)折叠或打开

  1. import java.util.*;

  2. /*
  3. 当元素自身不具备比较性,或者具备的比较性不是所需要的。
  4. 这时需要让容器自身具备比较性。
  5. 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。

  6. 当两种排序都存在时,以比较器为主。

  7. 定义一个类,实现Comparator接口,覆盖compare方法。


  8. */
  9. class Student implements Comparable//该接口强制让学生具备比较性。
  10. {
  11.     private String name;
  12.     private int age;

  13.     Student(String name,int age)
  14.     {
  15.         this.name = name;
  16.         this.age = age;
  17.     }

  18.     public int compareTo(Object obj)
  19.     {

  20.         //return 0;
  21.         
  22.         if(!(obj instanceof Student))
  23.             throw new RuntimeException("不是学生对象");
  24.         Student s = (Student)obj;

  25.         //System.out.println(this.name+"....compareto....."+s.name);
  26.         if(this.age>s.age)
  27.             return 1;
  28.         if(this.age==s.age)
  29.         {
  30.             return this.name.compareTo(s.name);
  31.         }
  32.         return -1;
  33.         /**/
  34.     }

  35.     public String getName()
  36.     {
  37.         return name;

  38.     }
  39.     public int getAge()
  40.     {
  41.         return age;
  42.     }
  43. }
  44. class TreeSetDemo2
  45. {
  46.     public static void main(String[] args)
  47.     {
  48.         TreeSet ts = new TreeSet();

  49.         ts.add(new Student("lisi02",22));
  50.         ts.add(new Student("lisi02",21));
  51.         ts.add(new Student("lisi007",20));
  52.         ts.add(new Student("lisi09",19));
  53.         ts.add(new Student("lisi06",18));
  54.         ts.add(new Student("lisi06",18));
  55.         ts.add(new Student("lisi007",29));
  56.         //ts.add(new Student("lisi007",20));
  57.         //ts.add(new Student("lisi01",40));

  58.         Iterator it = ts.iterator();
  59.         while(it.hasNext())
  60.         {
  61.             Student stu = (Student)it.next();
  62.             System.out.println(stu.getName()+"..."+stu.getAge());
  63.         }
  64.     }
  65. }

  66. class MyCompare implements Comparator
  67. {
  68.     public int compare(Object o1,Object o2)
  69.     {
  70.         Student s1 = (Student)o1;
  71.         Student s2 = (Student)o2;

  72.         int num = s1.getName().compareTo(s2.getName());
  73.         if(num==0)
  74.         {

  75.             return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
  76.             /*
  77.             if(s1.getAge()>s2.getAge())
  78.                 return 1;
  79.             if(s1.getAge()==s2.getAge())
  80.                 return 0;
  81.             return -1;
  82.             */
  83.         }

  84.         
  85.         return num;

  86.     }
  87. }

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