学号  姓名      成绩
1     张三      80
2     钱六      70
3     王五      60
4     李四      90
=========================
现在要按成绩高低输出,如何排序?

解决方案 »

  1.   


    public class Student {
    private String no;
    private String name;
    private double score;

    public Student(String no,String name, double score) {
    this.no = no;
    this.name = name;
    this.score = score;
    } public String getNo() {
    return no;
    } public void setNo(String no) {
    this.no = no;
    } public String getName() {
    return name;
    } public void setName(String name) {
    this.name = name;
    } public double getScore() {
    return score;
    } public void setScore(double score) {
    this.score = score;
    }

    @Override
    public String toString() {
    return no + "    " + name + "    " + score;
    }}import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class Main {
    public static void main(String[] args) {
    List<Student> students = new ArrayList<Student>();
    students.add(new Student("1","张三",80));
    students.add(new Student("2","钱六",70));
    students.add(new Student("3","王五",60));
    students.add(new Student("4","李四",90));

    //从大到小排序,若是从小到大排序,只需-1和1变换即可。
    Collections.sort(students, new Comparator<Student>() {
    public int compare(Student stu1, Student stu2) {
    if(stu1.getScore() > stu2.getScore()) {
    return -1;
    } else if(stu1.getScore() == stu2.getScore()) {
    return 0;
    } else {
    return 1;
    }
    }
    });

    for(Student stu : students) {
    System.out.println(stu);
    }
    }
    }定义一个Student类,来表示一行数据。然后用Collections接口中的sort方法排序,自定义Comparator。