让ArrayList内存放的对象类实现Collections接口
public class Student implements Comparable<Student> {
String name;
int grade;
Student(){}
Student(String name,int grade){
this.name=name;
this.grade=grade;
}
@Override
public int compareTo(Student o) {
return this.grade-o.grade;
}
}
import java.util.ArrayList;
import java.util.Collections;
public class Team {
static ArrayList<Student> student=new ArrayList<>();
public static void main(String[] args) {
Student x1=new Student("李隆会",59);
Student x2=new Student("张晨羊",80);
Student x3=new Student("肖泽融",60);
Student x4=new Student("李佳博",100);
student.add(x1);
student.add(x2);
student.add(x3);
student.add(x4);
Collections.sort(student);
for(Student s : student){
System.out.println(s.name+s.grade);
}
}
}
运行结果:
李隆会59
肖泽融60
张晨羊80
李佳博100