我有一个HashMap,其中值是ArrayLists,我正在尝试编写一个函数来接受这些HashMap的通用实例
HashMap<String, ArrayList<Integer>> myMap = new HashMap<String, ArrayList<Integer>>();
public static void foo(HashMap<?, ArrayList<?>> a) {}
public static void bar(HashMap<?, ? extends ArrayList<?>> a) {}
// Compilation Failure!
foo(myMap);
// This works, but why do I need ? extends ArrayList
bar(myMap)
错误信息为:
方法 Example 中的 foo(HashMap>) 不适用于参数 (HashMap>)
为什么需要在 extends ArrayList 中使用通配符?
我认为通过使用 ArrayList(不带 ? extends),可以将函数限制为只接受值为 ArrayList 的 HashMap。
同时,我知道以下泛型方法可行:
public static <K,V> void printer(HashMap<K, ArrayList<V>> list) { }
这种行为方式和我之前对 ArrayList<?>
的理解是一致的。有人能解释一下其中的微妙差别吗?
foo
生成的确切编译器错误,或者给出导致错误的foo
内部代码示例。实际上,这两个信息都会非常有帮助。 - Ken Wayne VanderLindeThe method foo(HashMap<?,ArrayList<?>>) in the type Example is not applicable for the arguments (HashMap<String,ArrayList<Integer>>)
- Michael Brewer-Davis