嗯,我这是在基础测试时写的,也考虑到了score是小数,给你参考下
----------------
/**
5、定义一个学生类, 需要有
姓名, 年龄, 考试成绩三个成员属性.
属性(成员变量)需要私有并提供get, set方法,
可以通过构造函数进行初始化。
*/
public class StudentDemo
{
public static void main(String[] args)
{
Student stu = new Student("harry", 15, 88.5) ; //构造一个学生对象;
System.out.println(stu.getName() + " " + stu.getAge() + " " +stu.getScore());
stu.setName("cobe");//设置 name ,age ,score;
stu.setAge(26);
stu.setScore(89.5);
System.out.println(stu.getName() + " " + stu.getAge() + " " +stu.getScore());
}
}
//将编译得到得Stduent.class和SortMyStuDemo类放同一目录一起编译;
class Student
{
public Student(String name, int age, double score)
{
this.name = name ;
this.age = age ;
this.score = score;
}
public String getName()//获取姓名
{
return name;
}
public int getAge()//获取年龄
{
return age;
}
public double getScore()//获取分数
{
return score;
}
public void setName(String name)//设置姓名
{
this.name = name;
}
public void setAge(int age)//设置年龄
{
this.age = age;
}
public void setScore(double score)//设置分数
{
this.score = score;
}
private String name;
private int age;
private double score;
}
----------------------------
import java.util.*;
public class SortMyStuDemo
{
public static void main(String[] args)
{
TreeSet<Student> ts = new TreeSet<Student>(new MyCompare());//创建树集,使用MyCompare类排序
ts.add(new Student("Harry" , 14, 87 ));
ts.add(new Student("Ameily", 12, 87.5));
ts.add(new Student("Cobber", 13, 85 ));
ts.add(new Student("Obamar", 17, 84.5));
ts.add(new Student("James" , 19, 86.5));
Iterator<Student> it = ts.iterator();
while(it.hasNext())
{ Student stu = it.next();
System.out.println("name="+stu.getName()+"... age="+ stu.getAge()+
"...score="+stu.getScore());
}
}
}
class MyCompare implements Comparator<Student>
{
public int compare(Student s1, Student s2)
{
double num = s1.getScore() - s2.getScore();
if ( num == 0) //分数相同则按照姓名排序
return s1.getName().compareTo(s2.getName());
else if (num > 0) //使用分数的升序排序;
return 1;
return -1;
}
}
/*
不使用comparTo方法直接比较分数;而是利用了compareTo方法的返回值就可比较分数大小,从而返回treeset排序的依据;
*/
|