在操做集合的過程當中,有時候須要對集合中的元素進行排序,如今就我所瞭解到的Compareble和Comparator兩種方法進行分析,理解其原理,按場景選擇合適的比較方法。html
Compareble是一個排序接口。若是一個類實現了該接口,就說明該類支持排序。即說明能夠經過Collections.sort()或 Arrays.sort()方法進行排序。此外,實現Comparable 接口的類的對象 能夠用做 「有序映射 ( 如 TreeMap)」 中的鍵或 「有序集合 (TreeSet)」 中的元素,而不須要指定比較器。java
該接口的定義以下:segmentfault
public interface Comparable<T> { public int compareTo(T o); }
咱們會經過例如a.compareTo(b)這樣的代碼來比較兩個類的大小,若是返回的int類型爲負數,意味着a<b,返回爲0的話,意味着a=b,返回爲正數,意味着a>b。ide
舉個例子:spa
覆寫compareTo : 設計一個有序Person類,實現了Comparable接口, 以年齡爲第一關鍵字,姓名爲第二關鍵字升序排序。設計
package java.lang; import java.util.*; public int compareTo(Person person) { int cop = age - person.getAge(); if (cop != 0) return cop; else return name .compareTo(person. name ); }
若是類的設計在開始時沒有考慮到Compare的問題,能夠經過外部的Comparator來進行實現。Comparator能夠根據本身的需求來設計想要的排序方式,好比說根據id升序排序,或者說根據id降序排序等。code
該接口的定義以下:htm
package java.util.*; public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }
若是一個類要實現Comparator接口:他必定要複寫compare()方法,可是能夠不實現equals()方法。由於在根類Object類中已經有了默認的該方法。一樣的 int compare(a,b)是比較a和b的大小,返回負數意味着 a<b,返回0意味着a=b,返回正數意味着a>b。對象
舉個例子:Student想根據age進行排序blog
Student stu[] = { new Student("張三" ,23), new Student("李四" ,26), new Student("王五" ,22)}; Arrays.sort(stu,new MyComparator()); List<Student> list = new ArrayList<Student>(); list.add( new Student("zhangsan" ,31)); list.add( new Student("lisi" ,30)); list.add( new Student("wangwu" ,35)); Collections.sort(list,new MyComparator()); /** * @desc MyComparator比較器 * 它是「Student的age的升序比較器」 */ private static class MyComparator implements Comparator<Person> { @Override public int compare(Student p1, Student p2) { return p1.getAge() - p2.getAge(); } }
其實咱們能夠發現,實現了Comparable這個排序接口,就意味着該集合內部是支持排序的,而Comparator這個接口像是一種比較器的存在,咱們若是須要更新下某個類的排序次序,則能夠創建一個相對應的比較器。
總的說來前者比較固定、內部,後者比較靈活、外部。
https://segmentfault.com/a/1190000002514187
http://www.cnblogs.com/skywang12345/p/3324788.html