[英]Java generic method call
考虑以下代码:
public class MainClass {
public static void main(String[] args) {
ArrayList<HashMap<String, Integer>> collection = new ArrayList<>();
ArrayList<HashMap<String, Integer>> outCollecttion = <String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);
}
public static <V extends Object, U extends Object, K extends Map<V, U>, J extends Collection<K>> Collection<K> doSomeWork(J collection) {
Collection<K> result = new ArrayList<>();
for (K element : collection) {
result.add(element); //here is supposed other code, this is just example
}
return result;
}
}
我想对包含某些通用类型的映射的通用集合做一些工作。 我知道Java很难确定复杂的泛型表达式,因此我在方法调用之前放置了显式类型:
<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<Integer, String>>>doSomeWork(collection)
但是编译器不会编译它。 我确实知道这可能与以下事实有关:我试图在泛型类型中使用泛型类型,但是我不知道如何在不使用强制类型转换的情况下编写此方法,而不是不赞成使用警告(我通常使用- Xlint:未选中的标志)。
首先,当您想显式提供类型参数时,必须从其类中调用该方法:
... = MainClass.<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);
其次,您的方法返回Collection<K>
,但是将变量声明为ArrayList<...>
。 以下对我有用:
Collection<HashMap<String, Integer>> outCollecttion = ...
您无需在分配中使用泛型。
Collection<HashMap<String, Integer>> outCollecttion = doSomeWork(collection);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.