首页 > 解决方案 > 从通用数组列表中查找最大值

问题描述

我想写一个方法来找到arraylist的最大值。它可以是整数或双精度类型。

我相信下面的代码适用于数组,但不适用于arraylist?

public static <T extends Comparable<T>> T maxValue(T[] array){       
     T max = array[0];
     for(T data: array){
          if(data.compareTo(max)>0)
              max =data;                
     }
     return max;
}

标签: java

解决方案


首先,应该Comparable<? super T>。其次,参数需要是Collection<T>(或List<T>)而不是数组。最后,您可以使用现有Collections.max(Collection<? extends T>)的来实现该方法。喜欢,

public static <T extends Comparable<? super T>> T maxValue(Collection<T> c) {
    return Collections.max(c);
}

推荐阅读