代码没有输出结果,能解释下为什么么,谢谢!
import java.util.Comparator;
import java.util.TreeSet;
import java.util.*;
class Foo implements Comparable<Object>
{
int num;
Foo(int num)
{
this.num = num;
}
public int getNum() {
return num;
}
public String toString()
{
return "num"+num;
}
public boolean equals(Object obj)
{
return true;
}
public int compareTo(Object obj)
{
Foo f = (Foo)obj;
return f.getNum()-this.getNum();
}
}
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
{
@SuppressWarnings("unchecked")
public static void main(String[] args)throws Exception{
TreeSet<Object> set = new TreeSet<Object> (new MyComparator());
set.add(new Foo(5));
set.add(new Foo(2));
set.add(new Foo(4));
set.add(new Foo(6));
Iterator<Object> it = set.iterator();
while(it.hasNext());
{
Foo str = (Foo)it.next();
System.out.println(str.getNum());
}
}
}
------解决思路----------------------
多了分号
while(it.hasNext());
------解决思路----------------------
while(it.hasNext());
多加了个分号!造成死循环!
因为没有调用it.next();所以it.hasNext()一直返回true;