今天上課,老師講到Arrays.sor()的時候說,這個可以對數組進行排序,於是當時腦海中立刻浮現出兩個問題:一、如果對類排序,一定要把實現什麼介面。二、實現了這個介面,Java怎麼知道一個類是否實現了某個介面。於是帶著這個問題做了一翻尋找。
對於類數組排序,調用Arrays.sort()即可,但是也只是對於基本類型的支援,如果對類進行排序,有如下兩種方法:
方法一,該類一定要實現Comparable<T>介面,並且實現public int compareTo(T o);方法。比較結果大的返回1,相等返回0,小於返回-1。該介面實現了泛型,如果聲明,則compareTo的參數則為Object。
實體類Student:
1 public class Student implements Comparable<Student>{
2 private String name = null;
3 private int age = 0;
4 public String getName() {
5 return name;
6 }
7 public void setName(String name) {
8 this.name = name;
9 }
10 public int getAge() {
11 return age;
12 }
13 public void setAge(int age) {
14 this.age = age;
15 }
16 public Student(String name, int age) {
17 this.name = name;
18 this.age = age;
19 }
20 @Override
21 public String toString() {
22 return String.format("Name=%s Age=%d", this.name, this.age);
23 }
24 @Override
25 public int compareTo(Student o) {
26 // 按名字排序
27 return this.name.compareTo(o.getName());
28 }
29 }
聲明一個Student數組,並且調用Arrays.sort()進行排序,然後輸出
1 Student[] stus = new Student[3];
2 stus[0] = new Student("Flowers", 12);
3 stus[1] = new Student("Boys", 13);
4 stus[2] = new Student("Zero", 21);
5 Arrays.sort(stus);
6 for(Student s : stus){
7 System.out.println(s.toString());
8 }
結果:
Name=Boys Age=13
Name=Flowers Age=12
Name=Zero Age=21
方法二,如果Student類並未實現Comparable<T>介面,則在調用Arrays.sort()時,要指定一個“比較子”,一個介面類Comparator<T>,所以使用時同時要寫出實現intcompare(T o1, T o2);方法的代碼。調用代碼如下:
1 Arrays.sort(stus, new Comparator<Student>(){
2 @Override
3 public int compare(Student o1, Student o2) {
4 return o1.getName().compareTo(o2.getName());
5 }
6 });
對於集合的排列,如ArrayList等實現了Collection<T>介面,List<T>是繼承於Collection<T>,所以實現List<T>的同樣適用。集合類的排序主要是用Collections.sort方法,Collections和Collection是不一樣的,前者是類,後者是介面。
一般我們主要使用兩個方法:
1.Collection.sort(List arg0);
這種是最簡單的一種排序方法,只需要實現他的Comparable 介面及實現public int compareTo(Object arg0)方法即可。
1 ArrayList<Student> list = newArrayList<Student>(3);
2 list.add(new Student("Flowers", 36));
3 list.add(new Student("Dog", 23));
4 list.add(new Student("About", 67));
5 Collections.sort(list);
2.Collection.sort(List arg0,Comparator arg1)
這種加入了比較子,具有更大的靈活性,便於管理,比較子可作為內部靜態類的,以便於管理。比較子必須實現Comparator介面。
1 Collections.sort(list, new Comparator<Student>(){
2 @Override
3 public int compare(Student o1, Student o2) {
4 // 按年齡排序
5 return o1.getAge() > o2.getAge()? 1:(o1.getAge() ==o2.getAge()? 0: -1);
6 }
7 });
以上兩種方法,得到的結果都一樣:
Name=Dog Age=23
Name=Flowers Age=36
Name=About Age=67
查看Collection.sort的原始碼,不難看出Java的思路,先講集合類轉化為數組,然後調用Arrays.sort方法進行排序,同時傳遞過去比較子,最後利用集合的迭代器將結果賦值回集合類中。
1 public static <T> void sort(List<T> list, Comparator<? super T> c) {
2 Object[] a = list.toArray();
3 Arrays.sort(a, (Comparator)c);
4 ListIterator i = list.listIterator();
5 for (int j=0; j<a.length; j++) {
6 i.next();
7 i.set(a[j]);
8 }
9 }