Java数组类的设计者提供给我们一个方便的模板方法用来排序:
Arrays.sort(ducks);
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a);
else
ComparableTimSort.sort(a, 0, a.length, null, 0, 0);
}
// 调用ComparableTimSort.sort中的代码片段
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi);
binarySort(a, lo, hi, lo + initRunLen);
return;
}
// 执行countRunAndMakeAscending中的代码片段
if (((Comparable) a[runHi++]).compareTo(a[lo]) < 0) { // Descending
while (runHi < hi && ((Comparable) a[runHi]).compareTo(a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
}
道理很简单,传入sort方法的对象数组必须是可排序的,也就是必须要实现comparable接口,否则就会报错(无法强转为Comparable类型)
countRunAndMakeAscending方法就是一个模板方法,使用方需要实现compareTo方法才能完成这个方法,而reverseRange方法是一个已经在当前类中实现的方法,所以这个实现算是一个模板方法的变种
我们来看一下实际应用:
public class Duck implements Comparable {
String name;
int weight;
public Duck(String name, int weight) {
this.name = name;
this.weight = weight;
}
@Override
public String toString() {
return "Duck{" +
"name='" + name + '\'' +
", weight=" + weight +
'}';
}
public int compareTo(Object o) {
Duck otherDuck = (Duck)o;
if (this.weight > otherDuck.weight) {
return 1;
} else if (this.weight == otherDuck.weight) {
return 0;
} else {
return -1;
}
}
}
测试类:
public class DuckTest {
@Test
public void testDuckComparable() {
Duck duck_01 = new Duck("duck_01", 1);
Duck duck_02 = new Duck("duck_02", 4);
Duck duck_03 = new Duck("duck_03", 3);
Duck[] ducks = {duck_01, duck_02, duck_03};
display(ducks);
System.out.println();
Arrays.sort(ducks);
display(ducks);
}
void display(Duck[] ducks) {
for (int i = 0; i < ducks.length; i++) {
System.out.println(ducks[i]);
}
}
}