package com.itheima;
import java.util.TreeSet;
public class test10 {
/**
* 10、声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)。
* @param args
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
TreeSet tr = new TreeSet();
tr.add(new Student("小李",21,89));
tr.add(new Student("小王",27,88));
tr.add(new Student("小张",23,95));
tr.add(new Student("小明",20,84));
tr.add(new Student("小孙",25,88));
System.out.println(tr);
}
}
@SuppressWarnings("rawtypes")
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;
}
public String toString(){ //重写toString方法
return this.name + this.age + "岁 " + this.score+"分";
}
}
|
|