自定义比较器。代码运行无结果,有同学看出有什么毛病么,给指点一下,谢谢!
- import java.util.Comparator;
- import java.util.TreeSet;
- import java.util.*;
- class Foo {
- int num;
- Foo(int num)
- {
- this.num = num;
- }
- public int getNum() {
- return num;
- }
- }
- class MyComparator implements Comparator {
- public int compare(Object o1,Object o2) {
- Foo f1 = (Foo)o1;
- Foo f2 = (Foo)o2;
-
- if (f1.getNum() > f2.getNum())
- {
- return 1;
- }
- else if (f1.getNum() == f2.getNum())
- {
- return 0;
- }
- else
- {
- return -1;
- }
- }
- }
- class comparedemo
- {
- public static void main(String[] args)throws Exception{
- TreeSet<Foo> set = new TreeSet<Foo>(new MyComparator());
- set.add(new Foo(1));
- set.add(new Foo(2));
- set.add(new Foo(8));
- set.add(new Foo(5));
- Iterator it = set.iterator();
- while(it.hasNext());
- {
- Foo str = (Foo)it.next();
- System.out.println(str.getNum());
- }
- }
- }
复制代码 |
|