有兩種方式,第一種方式在對象中實現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}
]
“`