题目
创建泛型方法,用继承 Comparable 的有界类型参数找出列表最大元素,并以 Optional 返回;空列表返回 Optional.empty。样例 [3,7,2,9,1] 返回 Optional[9];[] 返回 Optional.empty;[“banana”,“apple”,“cherry”] 返回 Optional[cherry]。
解题思路
方法签名为 <T extends Comparable
参考实现要点
首元素初始化避免了额外的哨兵值。遍历过程中只保存当前最大值,空间为常数级。上界 Comparable
常见错误
原文指出:类型参数不加上 Comparable 边界就无法调用 compareTo,必须写成 <T extends Comparable
验证方式
用 JDK 8 及以上编译,分别用整数列表、字符串列表与空列表调用 findMax,断言 Optional 的内容或是否为空。
代码示例
import java.util.List;
import java.util.Optional;
public class GenericMax {
public static <T extends Comparable<T>> Optional<T> findMax(List<T> list) {
if (list.isEmpty()) return Optional.empty();
T max = list.get(0);
for (T item : list) {
if (item.compareTo(max) > 0) {
max = item;
}
}
return Optional.of(max);
}
}