import java.util.*;
//学生类
public class Student implements Comparable{
public String name; //姓名
public int age; //年龄
public int score; //考试成绩
//构造函数,供类进行一些初始化信息
public Student(String name,int age,int score){
this.name=name;
this.age=age;
this.score=score;
}
@Override
//实现Comparable比较器的方法,按照自己的需求进行排序
public int compareTo(Object obj) {
// TODO Auto-generated method stub
if(!(obj instanceof Student) ){
throw new RuntimeException("不是学生类!");
}
Student s=(Student)obj;
int num=new Integer(score).compareTo(s.score);
if(num==0){
num=name.compareTo(s.name);
}
return num;
}
}
import java.util.TreeSet;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Student> tr=new TreeSet<Student>();
tr.add(new Student("张三",20,85));
tr.add(new Student("王伟",21,60));
tr.add(new Student("李莉莉",19,90));
tr.add(new Student("王冰",22,70));
tr.add(new Student("张川",18,80));
//增强for循环读取信息
for (Student s : tr) {
System.out.println("姓名:"+s.name+" 年龄:"+s.age+" 分数"+s.score);
}
}
}
|