本帖最后由 何伟超 于 2014-3-6 19:28 编辑
照着毕老师的代码抄了一遍,但运行时就只能添加一个元素。而且这一个也不对
import java.util.*;
class Student implements Comparable
{
private String name;
private int age;
Student(String name,int a)
{
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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class day1501
{
public static void main(String[] args)
{
TreeSet t = new TreeSet();
t.add(new Student("lisi1",20));
t.add(new Student("lisi2",30));
t.add(new Student("lisi3",41));
t.add(new Student("lisi4",24));
Iterator it = t.iterator();
while (it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
|