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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© smile_joe 中级黑马   /  2013-4-17 22:48  /  1700 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 smile_joe 于 2013-4-20 19:25 编辑
  1. /*
  2.         使用比较器对TreeSet集合元素进行判断
  3. */
  4. import java.util.*;
  5. class Test6 {
  6.         public static void main(String[] args) {
  7.                 Set s=new TreeSet(new Student());//可以使用到抽象内部类作为参数直接传递
  8.                 s.add(new Student("tom",34));
  9.                 s.add(new Student("joe",99));
  10.                 s.add(new Student("ket",99));
  11.                 s.add(new Student("mum",66));
  12.                 for(Iterator i=s.iterator();i.hasNext();) {//遍历输出
  13.                         System.out.println(i.next());
  14.                 }
  15.         }
  16. }
  17. class Student implements Comparator{
  18.         String name;
  19.         int id;
  20.         Student() {}
  21.         Student(String name,int id) {
  22.                 this.name=name;this.id=id;
  23.         }
  24.         public int compare(Object o1,Object o2){
  25.                 //System.out.println(o1); //要装入的元素
  26.                 //System.out.println(o2);//集合中已经存在的元素
  27.                 //System.out.println("--------------");

  28.                 Student s1=(Student)o1;
  29.                 Student s2=(Student)o2;
  30.                 int i=s1.id-s2.id;
  31.                 if(i>0) {
  32.                         return 1;
  33.                 }else if(i<0) {
  34.                         return -1;
  35.                 }else
  36.                         return s1.name.compareTo(s2.name);
  37.                         //compare(s1.name,s2.name);这个不能用?//s1.name.length()-s2.name.length();
  38.         }
  39.         public String toString() {
  40.                 return id+""+name;
  41.         }
  42. }
  43. 在倒数第5行,最后i=0时想再判断name,通过compareTo和字符串长度都可以,在用compare(o1,o2)不行呢?请帮忙看看指点下......十分感谢
复制代码

1 个回复

倒序浏览
您需要登录后才可以回帖 登录 | 加入黑马