public static <AnyType extends Comparable<? super AnyType>> AnyType findMax(AnyType[] arr) {
int maxindex = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[maxindex]) > 0) {
maxindex = i;
}
}
return arr[maxindex];
}
改进版,支持自定义比较方法。
public static <AnyType extends Comparable<? super AnyType>> AnyType findMax(AnyType[] arr,
Comparator<? super AnyType> cmp) {
int maxindex = 0;
for (int i = 1; i < arr.length; i++) {
if (cmp.compare(arr[i], arr[maxindex]) > 0) {
maxindex = i;
}
}
return arr[maxindex];
}