import java.util.Collection;
import java.util.Collections;
import java.util.Vector;
class Student implements Comparable<Student>
{
String name; // 名字
int score; // 成绩
Student(String name, int score)
{
this.name = name;
this.score = score;
}
public int compareTo(Student stu)
{
return stu.score - this.score; // 降序排序
}
public String toString() {
return "name = " + name + " " + "score = " + score ;
}
}
public class test
{
public static void main(String args[])
{
Vector<Student> stu = new Vector<Student>();
stu.add(new Student("1", 56));
stu.add(new Student("2", 25));
stu.add(new Student("3", 45));
stu.add(new Student("4", 36));
stu.add(new Student("5", 16));
Collections.sort(stu);
for (int i = 0;i < stu.size();i++) {
System.out.println(stu.get(i).toString());
}
}
}
关键地方是将这个类要实现Comparable<Student>
这个接口
这个接口中必须要重写compareTo
函数
最后使用Collections.sort(stu)
将容器里的东西排序