轉載:https://blog.csdn.net/wangtaocsdn/article/details/71500500
有時候需要對對象列表或數組進行排序,下面提供兩種簡單方式:
方法一:將要排序的對象類實現Comparable<>接口。
首先,創建學生類,我們將根據學生成績對學生進行排序:
/**
* 學生類
*/
class Student implements Comparable<Student>{
String name;
int age;
int score;
public Student(String name, int age,int score) {
this.name = name;
this.age = age;
this.score = score;
}
@Override
public int compareTo(Studento) {
// TODO Auto-generated method stub
return this.age - o.age;
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("大銘", 19, 89));
students.add(new Student("來福", 26, 90));
students.add(new Student("倉頡", 23, 70));
students.add(new Student("王磊", 18, 80));
System.out.println("排序前:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年齡:"+student.age+" 成績:"+student.score);
}
// 排序
Collections.sort(students);
System.out.println("排序后:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年齡:"+student.age+" 成績:"+student.score);
}
}
}
同理,也可以根據對象的其他屬性進行排序。
方法二:使用Comparator匿名內部類實現。
還是使用同一個例子,按成績將學生排序:
/**
* 學生類
*/
class Student {
String name;
int age;
int score;
public Student(String name, int age,int score) {
this.name = name;
this.age = age;
this.score = score;
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("大銘", 19, 89));
students.add(new Student("來福", 26, 90));
students.add(new Student("倉頡", 23, 70));
students.add(new Student("王磊", 18, 80));
System.out.println("排序前:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年齡:"+student.age+" 成績:"+student.score);
}
Collections.sort(students,new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.age-o2.age;
}
});
System.out.println("排序后:");
for (Student student : students) {
System.out.println("姓名:"+student.name+" 年齡:"+student.age+" 成績:"+student.score);
}
}
}
也可以實現按對象屬性將對象列表排序。