通用findMax方法

来源:互联网 发布:.net文件管理系统源码 编辑:程序博客网 时间:2024/06/08 08:18
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];}


原创粉丝点击