- Comparable
- Comparator
二者都用於實現集合中元素的比較、排序,Comparable是對象自己支持自比較時須要實現的接口,Comparator用於定義一個比較器,當對象不支持自比較或者不能知足你的要求時,能夠自定義一個對象比較器。java
Comparable實現樣例:算法
public class Person implements Comparable<Person> { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } 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(Person o) { int age2 = o.getAge(); return age > age2 ? 1 : (age == age2 ? 0 : -1); } }
@org.junit.Test public void testComparable() { Person p1 = new Person("lili", 20); Person p2 = new Person("jackson", 55); System.out.println(p1.compareTo(p2)); }
測試結果:-1json
Comparator實現樣例:ide
public class MyComparator implements Comparator { @Override public int compare(Object o1, Object o2) { int arg1 = Math.abs(((Integer) o1).intValue()); int arg2 = Math.abs(((Integer) o2).intValue()); return arg1 > arg2 ? 1 : (arg1 == arg2 ? 0 : -1); } }
@org.junit.Test public void testComparator() { List<Integer> list = new ArrayList<Integer>(); Integer a1 = new Integer(-1); Integer a2 = new Integer(2); Integer a3 = new Integer(-5); Integer a4 = new Integer(6); list.add(a1); list.add(a2); list.add(a3); list.add(a4); Collections.sort(list); System.out.println(JSON.toJSONString(list)); Collections.sort(list, new MyComparator()); System.out.println(JSON.toJSONString(list)); }
結果:
[-5,-1,2,6]
[-1,2,-5,6]測試
實現Comparable接口的對象比較很好理解,對於Comparator,咱們能夠看下集合比較的源碼:this
//java.util.Collections#sort(java.util.List<T>, java.util.Comparator<? super T>) public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } }
private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off, Comparator c) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i = low; i < high; i++) for (int j = i; j > low && c.compare(dest[j - 1], dest[j]) > 0; j--) swap(dest, j, j - 1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off, c); mergeSort(dest, src, mid, high, -off, c); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (c.compare(src[mid - 1], src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for (int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0) dest[i] = src[p++]; else dest[i] = src[q++]; } }
集合長度小於INSERTIONSORT_THRESHOLD(7),採用快速排序算法;不然,歸併排序算法spa