本帖最后由 潘东升 于 2012-5-16 18:11 编辑
import java.util.*;
class StudentSort
{
public static void main(String[] args)
{
//创建TreeSet对象,并把学生对象作为元素添加进去
TreeSet ts = new TreeSet();
ts.add(new Student("liYi",21,67));
ts.add(new Student("liEr",23,97));
ts.add(new Student("liSa",22,87));
ts.add(new Student("liSi",21,87));
ts.add(new Student("liWu",27,96));
//用迭代器获取并打印输出
Iterator it = ts.iterator();
System.out.println("按成绩排序后的结果\n"+"姓名\t"+"年龄\t"+"成绩");
while (it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"\t"+stu.getAge()+"\t"+stu.getExam());
}
}
}
class Student implements Comparable
{
private String name;
private int age,exam;
public Student(){}
public Student(String name, int age, int exam)
{
//在这里this用于区别成员变量和局部变量
this.name = name;
this.age = age;
this.exam = exam;
}
//覆盖Comparable接口的compareTo方法,并依次把成绩、年龄、姓名作为排序依据
public int compareTo(Object obj)
{
Student st = (Student)obj;
//System.out.println(this.name+"--equals--"+st.name);
if (this.exam>st.exam)
{
return 1;
}
if (this.exam==st.exam)
{
if (this.age>st.age)
{
return 1;
}
if (this.age==st.age)
{
//字符串已实现了Comparable接口,所以比较名字时直接调用
this.name.compareTo(st.name);
}
return 0;
}
return -1;
}
//姓名属性对应的set和get方法
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
//年龄属性对应的set和get方法
public void setAge(int age)
{
this.age=age;
}
public int getAge()
{
return age;
}
//考试成绩属性对应的set和get方法
public void setExam(int exam)
{
this.exam = exam;
}
public int getExam()
{
return exam;
}
}
输出时liSi被丢掉了
大家帮忙看看问题出在哪里 |