本帖最后由 陈雨 于 2013-4-13 14:04 编辑
学完泛型,正好有一道基础测试题目,拿来练手,按成绩排序不行,但按姓名排序打印成绩结果又可以.
//定义一个学生类, 需要有姓名, 年龄, 考试成绩三个成员属性,按成绩排序,用TreeSet和Comparator实现
import java.util.*;
class Test10
{
public static void main(String[] args)
{
TreeSet<Student> ts=new TreeSet<Student>(new Stucom());
ts.add(new Student("Jack",19,80));
ts.add(new Student("Tom",20,90));
ts.add(new Student("Lili",18,70));
ts.add(new Student("Lucy",21,85));
ts.add(new Student("Hobe",19,75));
Iterator<Student> it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next().getScore());
}
}
}
class Stucom implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
if(!(s1 instanceof Student))
throw new RuntimeException("不是学生对象");
if(!(s2 instanceof Student))
throw new RuntimeException("不是学生对象");
return s1.getScore().compareTo(s2.getScore ());
//这里如果换成getName,代码打印出来没问题,搞不懂为什么换成成绩就不行了.
}
}
class Student
{
private String name;
private int age;
private int score;
Student(String name,int age,int score)
{
this.name=name;
this.age=age;
this.score=score;
}
public void setShuXing(String n,int b,int c)//对私有变量设置值。
{
this.name=name;
this.age=age;
this.score=score;
}
public String getName( )//私有变量获取值。
{
return name;
}
public int getAge( )
{
return age;
}
public int getScore( )
{
return score;
}
}
|