【发布时间】:2019-10-29 11:10:05
【问题描述】:
如何告诉编译器我确定这个泛型类型有get方法?
我做了一些研究,让 T 扩展一些接口可能会有所帮助。 example1 example2
但是我必须为 get 方法扩展的确切接口是什么?
-
如何在 IDE 中搜索这个接口? 这样下次我就可以避免询问是否是 get 以外的其他方法
private static <T> ArrayList<T> trimstartend(ArrayList<T> rows,Date startdate ,Date endDate){ // if the date of current row is before the startdate, remove it for (Iterator<T> iterator = rows.iterator(); iterator.hasNext();) { T row = iterator.next(); if ((Date)row.get("Date").before(startdate) ) { // this line doesn't compile! Unresolved method get iterator.remove(); } } // if the date of current row is after the enddate, remove it for (Iterator<T> iterator = rows.iterator(); iterator.hasNext();) { T row = iterator.next(); if ((Date)row.get("Date").after(endDate)) { // this line doesn't compile! Unresolved method get iterator.remove(); } } return rows; }
其实T就是hashmap。但让我们在这里通用。
【问题讨论】:
-
HashMap实现了Map接口。该接口包含get方法。你可以写T extends Map<…, …>或者只是? extends Map<…, …>。 -
@MCEmperor 你的回答启发了我,我可以直接
<T extends HashMap<...,...> >我只想要get 方法,所以两者都有效,对吧? -
嗯,首先,您应该使用
Map而不是HashMap,这称为to program to an interface。其次,您不能只“挑选”一种方法(例如get)以某种类型实现;相反,您定义包含该方法的类型。 -
这一切都取决于您究竟想要实现什么,以及您为什么要使用泛型。
-
哦,请注意
Date类已过时;您应该改用java.time包中的类。
标签: java generics intellij-idea methods