在读《efficitive java》第12条:考虑实现Comparable接口
使用Comparable接口按对象按属性的优先级排序还是比较方便的
实例代码
package com.ctc.basic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Student implements Comparable<Student> {
private int number;
private String name;
private float score;
public Student(int number, String name, float score) {
this.number = number;
this.name = name;
this.score = score;
}
//排序优先级number-name-score
@Override
public int compareTo(Student c) {
// 如果number不等按number排序(增序
if (this.number != c.number) {
return this.number > c.number ? 1 : -1;
} else {
// 如果number和name都相等按score排序(降序)
if (this.name.equals(c.name)) {
return this.score < c.score ? 1 : -1;
}
// 如果number相等按name排序(增序)
return this.name.compareTo(c.name) > 0 ? 1 : -1;
}
}
@Override
public String toString() {
return "Student [number=" + number + ", name=" + name + ", score=" + score + "]";
}
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>() {
{
add(new Student(1, "a", 2));
add(new Student(3, "a", 3));
add(new Student(7, "a", 5));
add(new Student(5, "a", 2));
add(new Student(3, "a", 2));
add(new Student(7, "c", 2));
add(new Student(1, "b", 5));
add(new Student(7, "a", 2));
add(new Student(7, "c", 10));
}
};
Collections.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
输出结果为
Student [number=1, name=a, score=2.0]
Student [number=1, name=b, score=5.0]
Student [number=3, name=a, score=3.0]
Student [number=3, name=a, score=2.0]
Student [number=5, name=a, score=2.0]
Student [number=7, name=a, score=5.0]
Student [number=7, name=a, score=2.0]
Student [number=7, name=c, score=10.0]
Student [number=7, name=c, score=2.0]