【发布时间】:2016-08-18 16:43:03
【问题描述】:
我正在尝试创建一个通用方法 findMax(List list),它接受 LocalDate 列表或日期类型列表,并返回列表中的最大值。
Collections.max(List LocalDate) 和 Collections.max(List Date) 都可以正常工作,但我不知道如何让它返回正确的类型。
不太了解比较器在 Java 中的工作原理。
下面是我的尝试
static List<LocalDate> localDateList = new ArrayList<LocalDate>();
static List<Date> dateList = new ArrayList<Date>();
private <T> T findMax(List<T> list) {
return Collections.max(list);
}
public static void main(String[] args) throws ParseException, SQLException, JsonProcessingException {
localDateList.add(new Date(11 * 86400000).toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
localDateList.add(new Date(22 * 86400000).toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
localDateList.add(new Date(3 * 86400000).toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
localDateList.add(new Date(14 * 86400000).toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
localDateList.add(new Date(65 * 86400000).toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
dateList.add(new Date(11 * 86400000));
dateList.add(new Date(22 * 86400000));
dateList.add(new Date(3 * 86400000));
dateList.add(new Date(14 * 86400000));
dateList.add(new Date(65 * 86400000));
System.out.println(Collections.max(localDateList));
System.out.println(Collections.max(dateList));
System.out.println(findMax(localDateList));
System.out.println(findMax(dateList));
}
已编辑: 通过从
更改使其工作private <T> T findMax(List<T> list) {
return Collections.max(list);
}
到
private <T extends Object & Comparable<? super T>> T findMax(List<T> list) {
return Collections.max(list);
}
【问题讨论】:
-
Collections.max已经返回“正确”类型。例如,String s = Collections.max(yourListOfString)将编译。 -
贴出的代码有什么问题?为什么你试图将 Collections.max() 包装成一个做同样事情的方法?如果你真的想要,为什么不使用与 Collections.max() 完全相同的泛型类型?
-
它告诉你它是一个对象,因为类型擦除。泛型类型仅在编译时由编译器知道,并且仅在那时才相关。他们在那里尽可能避免不安全的演员表。
-
@OuYe 顺便说一下,java.time 类取代了旧的 java.util.Date/.Calendar 类。不打算混合。坚持使用 java.time。仅在需要处理尚未更新为 java.time 类型的旧代码时才使用旧类。
-
如果你想编译你的
findMax方法,你必须将你的findMax方法的泛型类型从<T>更改为<T extends Object & Comparable<? super T>>,但我不明白这一点。
标签: java generics collections