Compareble接口
可以直接通過Arrays.sort 對數組進行排序
import java.util.Arrays;
public class Student implements Comparable<Student>
{
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score
+ "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if (this.age < o.age) {
return -1;
}
if (this.age > o.age) {
return 1;
} else {
if (this.score < o.score) {
return -1;
}
if (this.score > o.score) {
return 1;
}
}
return 0;
}
public static void main(String[] args) {
Student stu[]={
new Student("馬超", 68, 88),
new Student("趙雲", 30, 90),
new Student("關二個", 33, 99),
new Student("張飛",32, 92)
};
Arrays.sort(stu);
for (int i = 0; i < stu.length; i++) {
System.out.println(stu[i]);
}
}
}
輸入結果 Student [name=趙雲, age=30, score=90]Student [name=張飛, age=32, score=92]
Student [name=關二個, age=33, score=99]
Student [name=馬超, age=68, score=88]
如果 Student類沒有實現comparable 則會拋出Student cannot be cast to java.lang.Comparable (student類不能被拋到java.lang.Comparable )說明arrays.sort()實現是根據compareble進行數組排序的。引用一老兄的話:java中的對象排序永遠都是以Comparable 接口爲標準的。、
另一種比較器 comparator
comparator接口中實現的方法
compare(T o1,To2)---比較用來比較的2個參數
compare 主要作用是用來對已經寫好的類,但是沒有實現comparable 接口進行的補充。
http://blog.csdn.net/cz1029648683/article/details/6666855 一位老兄的文章。