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

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

问题描述

我有一个HashMap其中的值的ArrayList,而我试图写一个函数来接受这些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)

该错误消息

该方法富(HashMap的&LT;?,ArrayList的&LT;&GT;&GT;)中的类型示例是不适用
  对于参数(的HashMap&LT;弦乐,ArrayList的&LT;整数GT;&GT; )。

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

为什么我需要有一个通配符的扩展ArrayList的?

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

我认为,通过让的ArrayList&LT;&GT;(?不用扩展,我可以限制功能只与ArrayList的价值观HashMaps这样。

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&LT;&GT; 会工作。有人可以解释这里的微妙之处?

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

推荐答案

通配符语法是故意设计(MIS)导致人们相信它的任何类型相匹配。这适用于简单的情况下

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

由于新1级的
如果取值 T亚型 G&LT; S&GT; G&LT亚型;?扩展T&GT; 。应用在的情况下, S =名单,LT;弦乐&GT; T =清单&LT;&GT;

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

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

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