有两种方式,第一种方式在对象中实现Compartable接口,第二种方式为创建一个实现实现Comparator接口,或者通过匿名内部类的方式
第一种方式:在对象中实现Compatable接口
//首先创建一个Student对象
package ListSortDemo;
public class Student implements Comparable<Student>{
private String name;
private int age;
private int secore;
public Student() {
}
public Student(String name, int age, int secore) {
this.name = name;
this.age = age;
this.secore = secore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", secore=" + secore +
'}'+'\n';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSecore() {
return secore;
}
public void setSecore(int secore) {
this.secore = secore;
}
//重写compareTo()方法
@Override
public int compareTo(Student o) {
return this.secore - o.secore; //此处通过分数升序排序
}
}
//测试类
public class ArrayLisetSort {
public static void main(String[] args) {
ArrayList<Student> arr = new ArrayList<>();
arr.add(new Student("张三",18,56));
arr.add(new Student("李四",15,57));
arr.add(new Student("王五",23,32));
arr.add(new Student("王二",30,44));
Collections.sort(arr);
System.out.println(arr);
}
运行结果:
[Student{name=’王五’, age=23, secore=32}
, Student{name=’王二’, age=30, secore=44}
, Student{name=’张三’, age=18, secore=56}
, Student{name=’李四’, age=15, secore=57}
]
“`