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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈国华 中级黑马   /  2014-12-15 22:51  /  840 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自定义比较器。代码运行无结果,有同学看出有什么毛病么,给指点一下,谢谢!
  1. import java.util.Comparator;
  2. import java.util.TreeSet;
  3. import java.util.*;
  4. class Foo {
  5.          int num;
  6.          Foo(int num)
  7.          {
  8.                 this.num = num;
  9.          }
  10.          public int getNum() {
  11.           return num;
  12.          }
  13. }
  14. class MyComparator implements Comparator {

  15.          public int compare(Object o1,Object o2) {
  16.                  Foo f1 = (Foo)o1;
  17.                  Foo f2 = (Foo)o2;
  18.           
  19.           if (f1.getNum() > f2.getNum())
  20.           {
  21.            return 1;
  22.           }
  23.           else if (f1.getNum() == f2.getNum())
  24.           {
  25.            return 0;
  26.           }
  27.           else
  28.           {
  29.            return -1;
  30.           }
  31.         }
  32. }
  33. class comparedemo
  34. {
  35.         public static void main(String[] args)throws Exception{
  36.         TreeSet<Foo> set = new TreeSet<Foo>(new MyComparator());
  37.          set.add(new Foo(1));
  38.          set.add(new Foo(2));
  39.          set.add(new Foo(8));
  40.          set.add(new Foo(5));
  41.         Iterator it = set.iterator();
  42.          while(it.hasNext());
  43.          {
  44.                  Foo str = (Foo)it.next();
  45.                  System.out.println(str.getNum());
  46.          }
  47.         }
  48. }
复制代码

0 个回复

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