唐杨 发表于 2012-8-22 18:57
代码是有问题的,而且最后还少了两个 大括号.} }
你的compareTo方法写的有问题.
package javatest2;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new student("lis1", 1));
ts.add(new student("lis2", 2));
ts.add(new student("lis3", 3));
Iterator it = ts.iterator();
while(it.hasNext())
{
student t = (student)it.next();
System.out.println(t.getName() + "..." + t.getAge());
}
}
}
class student implements Comparable
{
private String name;
private int age;
student(String name, int age)
{
this.name = name;
this.age = age;
}
@Override
public int compareTo(Object obj)
{
if(!(obj instanceof student))
throw new RuntimeException("非学生对象");
student s = (student)obj;
if(this.age > s.age)
return 1;
else if(this.age == s.age)
return 0;
else
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
还是有问题啊·大哥 |