package com.itheima;
import java.util.TreeSet;
/**
* 声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)
* @author Administrator
*
*/
public class Test10 {
public static void main(String[] args){
//创建Student对象
Student stu = new Test10().new Student("aaa", 18, 85);
Student stu1 = new Test10().new Student("bbb", 19, 97);
Student stu2 = new Test10().new Student("ccc", 13, 97);
Student stu3 = new Test10().new Student("ddd", 20, 87);
Student stu4 = new Test10().new Student("eee", 18, 57);
//创建TreeSet对象
TreeSet<Student> treeSet = new TreeSet<Student>();
treeSet.add(stu);
treeSet.add(stu1);
treeSet.add(stu2);
treeSet.add(stu3);
treeSet.add(stu4);
//打印treeset集合
System.out.println(treeSet);
}
/**
*
* @author Administrator
*decription(学生类),实现Comparable接口
*/
class Student implements Comparable{
/**field name 姓名*/
private String name;
/**field age 年龄*/
private int age;
/**field score 分数*/
private float score;
/**构造方法*/
public Student(String name,int age,float score){
this.name = name;
this.age = age;
this.score = score;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = age;
}
public float getScore(){
return this.score;
}
public void setScore(float score){
this.score = score;
}
//按顺序输出时的比较方法
@Override
public int compareTo(Object o) {
Student student = (Student)o;
//先按照分数比较,分数相同按照名字
if(this.score > student.score){
return -1;
}else if(this.name.compareTo(student.name)>0){
return 1;
}else if(this.name.compareTo(student.name)<0){
return -1;
}
return 0;
}
@Override
public String toString(){
return "[姓名:"+name+",年龄:"+age+",分数:"+score+"]";
}
}
}
|