Java泛型方法调用
考虑以下代码:Java泛型方法调用,java,generics,Java,Generics,考虑以下代码: public class MainClass { public static void main(String[] args) { ArrayList<HashMap<String, Integer>> collection = new ArrayList<>(); ArrayList<HashMap<String, Integer>> outCollecttion = <S
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;
}
}
public类MainClass{
公共静态void main(字符串[]args){
ArrayList集合=新建ArrayList();
ArrayList OutCollection=doSomeWork(集合);
}
公共静态收集doSomeWork(J收集){
收集结果=新建ArrayList();
for(K元素:集合){
result.add(element);//这里假设有其他代码,这只是一个示例
}
返回结果;
}
}
我想对包含一些泛型类型映射的泛型集合进行一些工作。我知道Java很难计算复杂的泛型表达式,所以我将显式类型放在方法调用之前:
<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<Integer, String>>>doSomeWork(collection)
doSomeWork(集合)
但编译器不会编译那个。我知道这可能与我试图在泛型类型中使用泛型类型有关,但我不知道如何在不使用强制类型转换的情况下编写此方法,而不使用弃用警告(我通常使用-Xlint:unchecked标志进行编译)。您不需要在赋值中使用泛型
Collection<HashMap<String, Integer>> outCollecttion = doSomeWork(collection);
Collection outcollection=doSomeWork(收集);
首先,当您想显式提供类型参数时,必须从其类调用该方法:
... = MainClass.<String, Integer, HashMap<String, Integer>, ArrayList<HashMap<String, Integer>>>doSomeWork(collection);
…=主类。doSomeWork(集合);
其次,方法返回集合
,但变量声明为ArrayList
。以下是我的作品:
Collection<HashMap<String, Integer>> outCollecttion = ...
Collection outcollection=。。。
也许您在ArrayList
中意外地切换了整数和字符串?谢谢您指出这一点,但它仍然没有用。编辑了有问题的代码。你试过编译它吗?因为它不会<代码>错误:(12,72)java:不兼容的类型;没有任何类型变量(s)v,u,k的存在,所以java. UTILITE集合符合JavaUTILARYLIST所需:java. UTIL.AARYLIST:java。UTI.Cuffic集合/<代码>,这绝对是有帮助的。非常感谢。