排序的问题

danliandejintou 2011-05-04 07:40:21
学号 姓名 成绩
1 张三 80
2 钱六 70
3 王五 60
4 李四 90
=========================
现在要按成绩高低输出,如何排序?
...全文
170 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
茫茫大海 2011-05-04
  • 打赏
  • 举报
回复

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。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧