import java.util.*;
/*
* 声明类Student,包含3个成员变量:name、age、score,创建5个对象
* 装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题).
*/
public class Test10 {
public static void main(String[] args) {
//声明TreeSet
TreeSet tr = new TreeSet();
tr.add(new Student("A",21,89));
tr.add(new Student("B",27,88));
tr.add(new Student("C",23,95));
tr.add(new Student("D",20,84));
tr.add(new Student("E",25,88));
System.out.println(tr);
}
}
class Student implements Comparable{
String name;
int age;
int score;
//构造方法
Student(String name,int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
//按顺序输出时的比较方法
public int compareTo(Object o){
Student stu = (Student) o;
//先按照分数比较,分数相同按照名字
if(this.score>stu.score) return 1;
else if(this.score<stu.score) return -1;
else if(this.name.compareTo(stu.name)>0) return 1;
else if(this.name.compareTo(stu.name)<0)return -1;
return 0;
}
//重写toString方法
public String toString(){
return this.name+'\0'+this.age+'\0'+this.score;
}
}
//报错了 java.lang.ClassCastException
|
|