|
发表于 2020-5-22 16:21:16
|
显示全部楼层
本帖最后由 java2python 于 2020-5-22 16:28 编辑
java有比较器的,什么排序法,你能做的过java团队?Collections集合可以排序,ArrayList也是属于集合的,Student类需要实现比较器,然后交给集合排序就行了
import java.util.ArrayList;
import java.util.Collections;
public class SortTest {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<Student>();
for(int i=0;i<5;i++) students.add(new Student(i+1,"student0"+i,(int)(Math.random()*100)));
Collections.sort(students);
for(int i=0;i<2;i++) System.out.println(students.get(i));
}
}
class Student implements Comparable<Student> {
int stuId;
String stuName;
int score;
public Student(int stuId, String stuName, int score) {
this.stuId = stuId;
this.stuName = stuName;
this.score = score;
}
@Override
public int compareTo(Student o) {
return score-o.score;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", score=" + score +
'}';
}
}
|
|