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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 唐晓 中级黑马   /  2013-1-20 14:50  /  1137 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Student implements Comparable//该接口强制让学生具备比较性。
  2. {
  3.         private String name;
  4.         private int age;

  5.         Student(String name,int age)
  6.         {
  7.                 this.name = name;
  8.                 this.age = age;
  9.         }

  10.         public int compareTo(Object obj)
  11.         {

  12.                 //return 0;
  13.                
  14.                 if(!(obj instanceof Student))
  15.                         throw new RuntimeException("不是学生对象");
  16.                 Student s = (Student)obj;

  17.                 //System.out.println(this.name+"....compareto....."+s.name);
  18.                 if(this.age>s.age)
  19.                         return 1;
  20.                 if(this.age==s.age)
  21.                 {
  22.                         return this.name.compareTo(s.name);
  23.                 }
  24.                 return -1;
  25.                 /**/
  26.         }

  27.         public String getName()
  28.         {
  29.                 return name;

  30.         }
  31.         public int getAge()
  32.         {
  33.                 return age;
  34.         }
  35. }
复制代码
  1. class MyCompare implements Comparator
  2. {
  3.         public int compare(Object o1,Object o2)
  4.         {
  5.                 Student s1 = (Student)o1;
  6.                 Student s2 = (Student)o2;

  7.                 int num = s1.getName().compareTo(s2.getName());
  8.                 if(num==0)
  9.                 {

  10.                         return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
  11.                         /*
  12.                         if(s1.getAge()>s2.getAge())
  13.                                 return 1;
  14.                         if(s1.getAge()==s2.getAge())
  15.                                 return 0;
  16.                         return -1;
  17.                         */
  18.                 }

  19.                
  20.                 return num;

  21.         }
  22. }
复制代码
这两种比较器有什么区别?

评分

参与人数 1黑马币 +9 收起 理由
黄锦成 + 9 神马都是浮云

查看全部评分

2 个回复

倒序浏览
本帖最后由 赵彦辉 于 2013-1-20 15:17 编辑

第一种方式为:让元素自身具备比较性,元素需要实现comparable接口,覆盖compareTo()方法,这种方式成为元素的自然顺序。
但是当元素自身不具备比较性时,或者具备的比较性不是所需要的,这时就需要让集合自身具备比较性。在集合初始化时,就有了比较方式。
定义比较器,将比较器对象作为参数传递给TreeSet集合的构造函数。
当两种排序都存在时,以比较器为主;
说的更直接点就是你写的第一个比较方式为默认的比较方式,程序运行时会首先调用它进行比较。
当你对默认的比较方法不满意时,可以自己定义比较器,让程序按照自己写的比较器方式进行比较。

评分

参与人数 1黑马币 +9 收起 理由
黄锦成 + 9 赞一个!

查看全部评分

回复 使用道具 举报
就像二楼所说的那样,在这补充一下,如果一个类已经开发完成,并且该类不是有你自己开发的,在其他程序中多次用到了这个类,如String,它是按自然法则进行排序的(不适合大幅度修改代码,你也改不了),又或者该类并没有实现Comparable接口,无法对其进行排序操作,这时候就应该自定义比较器,实现Comparator接口

评分

参与人数 1黑马币 +9 收起 理由
Rancho_Gump + 9 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马