如何使用不确定的“?"为Java通用地图添加值?值类型 [英] How to add values for java generic map with undetermined "?" value type

查看:50
本文介绍了如何使用不确定的“?"为Java通用地图添加值?值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在jdk 8示例中看到了这种声明:

I've seen this kind of declaration in jdk 8 sample:

    Map<String, ?> map = new HashMap<>(3);//OK

但是当我尝试为地图"添加价值时,我没有成功:

But when I tried to add value to "map", I didn't succeed:

    map.put("abc", Optional.of(5));
    map.put("kk", "xyz");

两者均无法编译.我想知道:

Both fail to compile. I wish to know:

(1)是什么?"在上面的地图声明中指明?

(1) What does "?" indicate in Map declaration above?

(2)如何为该地图"赋予值?

(2) How to give values to this "map"?

推荐答案

问题(1)

? is called wildcard generic type.It can be used with any type,
but you need to specify type fist as Map is an abstract class.

问题(2)

您可以使用上限"或下限"为该地图赋予价值.

以下是使用上限或下限的准则

The following are guidelines when using upper bound or lower bound

? extends Type   - is used for read access only
? super Type     - is used for write access only.

PECS 简写为产生(写入权限)-使用扩展,而消耗(读取访问权限)-使用超级

PECS in short Produces(write acccess) -uses Extends while Consumes(read access) - uses Super

Map<String, ? super Object> map = new HashMap<>(3);//OK
    map.put("abc",Optional.of(5));
    map.put("kk","xyz");
map.forEach((k,v)->System.out.println(k+"\t"+v));

输出

kk  xyz
abc Optional[5]

Process finished with exit code 0

附加说明

无限制通配符?

 List<?> l = new ArrayList<String>();

具有上限的通配符?扩展类型

 List<? extends Exception> l = new ArrayList<RuntimeException>();

下限通配符?超级类型

 List<? super Exception> l = new ArrayList<Object>();

这篇关于如何使用不确定的“?"为Java通用地图添加值?值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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