java - 从通用数组列表中查找最大值
问题描述
我想写一个方法来找到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;
}
解决方案
首先,应该是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);
}
推荐阅读
- r - 在 iris 数据集中发现额外的列
- python - Pandas 数据框中带有 group_by 的 if-else 语句
- reactjs - 应用程序中对 antd 组件的多次覆盖
- node.js - Node JS Express 应用程序中的 MaxListenersExceededWarning
- python - 使用 Jupyter 运行 python 包
- java - redisTemplate.executePipelined 可能导致 SocketTimeOut
- wolfram-mathematica - 如何使 PopupMenu[x, {1, 2, 3, 4, 5, 6}] 列出其项目不只是一列?
- javascript - 如何从javascript中的回调将元素添加到全局数组
- azure - Azure 函数的 Web UI 用于监视和重播排队的项目
- rust - to_owned() 什么时候不克隆?