62,614
社区成员
发帖
与我相关
我的任务
分享
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);
}
}
}