自定义Array.sort()方法
Arrays.sort()方法采用的是模板方法模式,步骤为mergeSort --- comparaTo --- swap
原理:
所以如果自定义排序方法时,需要实现comparaTo()方法
comparaTo()方法的实现为:
public class Duck implements Comparable<Object> {
String duckStr;
public Duck(String str){
this.duckStr = str;
}
@Override
public int compareTo(Object obj) {
Duck str1 = (Duck)obj;
if (this.duckStr.length() < str1.duckStr.length()) {
return -1;
} else if (this.duckStr.length() == str1.duckStr.length()) {
return 0;
} else {
return 1;
}
}
}
排序:
Duck[] duck = { new Duck("abc"), new Duck("a") };
Arrays.sort(duck);
for (int i = 0; i < duck.length; i++) {
System.out.println(duck[i].duckStr);
}
结果:
a
abc