class TreeSetDemo1
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi07",22));
ts.add(new Student("lisi05",18));
ts.add(new Student("lisi02",20));
ts.add(new Student("lisi04",2));
ts.add(new Student("lisi03",29));
ts.add(new Student("lisi09",52));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException
Student s = (Student)obj;
System.out.println(this.name+"...compareto..."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)
{
return this.name.compareTo(s.name);
}
return -1;
}
}
//错误是在37行。 请帮忙改正 多谢。 |