1.定义一个Student类,包括学号,姓名,成绩三个字段,生成get,set和toString方法,实现Comparable接口,重写toCompare方法,方法里就是本题的逻辑,先按成绩比较,再按学好比较,使用TreeSet不实现这个接口会报错。
package Collection;
public class Student implements Comparable<Student> {
private long sno;
private String name;
private int score;
public long getSno() {
return sno;
}
public void setSno(long sno) {
this.sno = sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if (this.score < o.score) {
return 1;
} else if (this.score > o.score) {
return -1;
} else {
if(this.sno<o.sno) {
return 1;
}else {
return -1;
}
}
}
@Override
public String toString() {
return "Student [sno=" + sno + ", name=" + name + ", score=" + score + "]";
}
}
2.然后写测试类,生成十个学生,然后插入treeset,直接遍历输出就是排序好的结果。
package Collection;
import java.util.Random;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<Student>();
for(int i=0;i<10;i++) {
Student stu=new Student();
stu.setName("student"+i);
stu.setSno(170201+i);
stu.setScore(90+new Random().nextInt(10));
ts.add(stu);
}
for(Student stu:ts) {
System.out.println(stu);
}
}
}
最后贴一个运行结果
