本帖最后由 范龙波 于 2013-5-1 18:27 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new Student("zhangsan",18));
t.add(new Student("lisi",22));
t.add(new Student("wangmazi",33));
//t.add(new Student("wangmazi01",33));
Iterator i=t.iterator();
while (i.hasNext())
{
Student.sop(i.next());
Student s=(Student)i.next();
System.out.println(s.GetName()+s.GetAge());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
public String GetName()
{
return name;
}
public int GetAge()
{
return 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;
if(this.age>s.age)
return 1;
if(this.age==s.age)
return 0;
return -1;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
} //这个代码打印的结果出现了异常,可我没有找到我哪里写错了,能告诉下我哪里的代码写错了吗谢谢。编译没有错误,可是打印却出问题。
|