import java.util.*;
public class Test10
{
public static void main(String[] args)
{
//创建一个TreeSet集合
TreeSet<Student> ts = new TreeSet<Student>(new Mycompare());
//向集合添加五个学生对象
ts.add(new Student("张三",19,88));
ts.add(new Student("李四",18,97));
ts.add(new Student("王五",21,85));
ts.add(new Student("赵六",19,85));
ts.add(new Student("钱七",22,93));
//定义一个变量表示成绩排名
int rank = 1;
//循环遍历打印结果
for (Student s : ts)
System.out.println((rank++)+"--"+s.getName()+" "+s.getAge()+" "+s.getScore());
}
}
class Student
{
//定义成员属性
private String name;
private int age;
private double score;
//创建有参数构造函数,要求成员创建就要对属性初始化
Student(String name,int age,double score)
{
this.name = name;
this.age = age;
this.score = score;
}
//创建set方法便于修改成员属性
public void setName()
{
this.name = name;
}
public void setAge()
{
this.age = age;
}
public void setScore()
{
this.score = score;
}
//创建获取属性的get方法
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public double getScore()
{
return score;
}
}
//自定义比较器,主要是按照成绩由高到低排序
class Mycompare implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
//先判断成绩,按成绩由高到低排序
if (s2.getScore() > s1.getScore())
return 1;
else if (s2.getScore() == s1.getScore())
//如果成绩相同,再判断名字和年龄,都相同为同一人;同成绩不同人的排名不分先后(按照添加进集合的先后排序)
return (s1.getName().equals(s2.getName()) && s1.getAge()==s2.getAge())? 0 : 1 ;
else
return -1;
}
} |