java中Collections對自定義物件進行sort()
阿新 • • 發佈:2019-01-10
基礎學生類
package itcast02;
public class Student implements Comparable<Student> {
// 學生姓名
private String name;
// 學生年齡
private int age;
// 無參構造
public Student() {
super();
}
// 帶參構造
public Student(String name, int age) {
super();
this.name = name;
this .age = age;
}
// getXxx() setXxx()方法
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;
}
@Override
public int compareTo(Student s) {
int num = this.age - s.age;
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
}
實現類
package itcast02;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Collections不僅可以針對ArrayList儲存基本包裝類的元素排序,還可以對自定義物件進行排序。
*
* @author lgt
*
*/
public class CollectionsDemo {
public static <T> void main(String[] args) {
// 建立集合物件
List<Student> list = new ArrayList<Student>();
// 建立學生物件
Student s1 = new Student("荊軻", 20);
Student s2 = new Student("亞瑟", 49);
Student s3 = new Student("魯班七號", 28);
Student s4 = new Student("蘭陵王", 36);
Student s5 = new Student("后羿", 12);
// 新增學生物件到list
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
// 遍歷
System.out.println("------------原始順序---------------");
for (Student s : list) {
System.out.println(s.getName() + "---" + s.getAge());
}
// //自然排序
// Collections.sort(list);
//
// //遍歷
// System.out.println("------------自然排序---------------");
// for(Student s : list){
// System.out.println(s.getName() + "---" + s.getAge());
// }
// 如果同時有比較器排序和自然排序,以比較器排序結果為最終結果
// 比較器排序
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
return num2;
}
});
// 遍歷
System.out.println("------------比較器排序--------------");
for (Student s : list) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}