带有 ArrayList 通配符的 Java HashMap [英] Java HashMap with ArrayList wildcards

查看:89
本文介绍了带有 ArrayList 通配符的 Java HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HashMap,其中的值是 ArrayLists,我正在尝试编写一个函数来接受这些 HashMaps 的通用实例

I have a HashMap where the values are ArrayLists, and I'm trying to write a function to accept generic instances of these HashMaps

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>).

The method foo(HashMap<?,ArrayList<?>>) in the type Example is not applicable for the arguments (HashMap<String,ArrayList<Integer>>).

为什么我需要为 extends ArrayList 使用通配符?

Why do I need to have a wildcard for the extends ArrayList?

我认为通过使用 ArrayList(没有 ? extends),我可以将函数限制为仅具有 ArrayList 值的 HashMap.

I thought that by having ArrayList<?>(without the ? extends), I could restrict the function to only HashMaps with ArrayList values.

我也知道以下通用方法有效:

I also know that the following generic method works:

public static <K,V> void printer(HashMap<K, ArrayList<V>> list) { }

我认为 ArrayList<?> 会起作用的行为.有人能解释一下这里的微妙之处吗?

Which behaves how I thought ArrayList<?> would work. Can someone explain the subtleties here?

推荐答案

通配符语法被故意设计为(错误地)让人们相信它匹配任何类型.这适用于简单的情况

The wildcard syntax was deliberately designed to (mis)lead people to believe it matches any type. This works for simple cases

List<?> <= List<String> // OK, right is subtype of left

但请记住,它仅适用于第 1 层,而不适用于更深的层次

But remember, it only works on the 1st level, not deeper

List<List<?> <= List<List<String>>  // FAIL

没问题

List<? extends List<?>> <= List<List<String>>

因为新的第一级?.如果 ST 的子类型,则 GG.应用在S=ListT=List的情况下.

because of the new 1st level ?. If S is subtype of T, G<S> is subtype of G<? extends T>. Apply that in case ofS=List<String>, T=List<?>.

这篇关于带有 ArrayList 通配符的 Java HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆