为什么MAP使用通用通配符扩展对象不能容纳任何类型? [英] Why a MAP use generic wildcard extends Object cannot hold any type?

查看:63
本文介绍了为什么MAP使用通用通配符扩展对象不能容纳任何类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,问题标题令人困惑.这就是我的意思.

Sorry if the question title is confusing. Here is what I mean.

我有一个 Map< String,吗?扩展Object>studentDetails = new HashMap<>(); ,我希望它包含任何随机类型.

I have a Map<String, ? extends Object> studentDetails = new HashMap<>(); and I want it to hold any random types.

我放进去

studentDetails.put("name", "John"); 
studentDetails.put("friendNames", Arrays.aslist("Kenny","Peter","friend3"));
studentDetails.put("courses", new HashSet<String>());
studentDetails.put("age",18);

编译器给我:

必填类型:捕获?扩展对象,提供:字符串

required type: capture of ? extends Object, Provided: String

必填类型:捕获?扩展对象,提供:ArrayList

required type: capture of ? extends Object, Provided: ArrayList

必填类型:捕获?扩展对象,提供:哈希集

required type: capture of ? extends Object, Provided: HashSet

必填类型:捕获?扩展对象,提供:整数

required type: capture of ? extends Object, Provided: Integer

为什么错了?不应该吗?扩展对象捕获任何类型?如果我将其更改为Map< String,Object> ;,那么它将起作用.

Why is it wrong? Shouldn't ? extends Object captures any type? If I change it to Map<String, Object>, then it works.

任何帮助将不胜感激!谢谢!

Any help would be appreciated! Thanks!

推荐答案

出于相同的原因,您不能这样做:

For the same reason you can't do this:

List<Integer> ints = new ArrayList<>();
        
List<? extends Object> objs;

List< Integer> List< ;?的子类型?扩展Object> ,因此您可以将 List< Integer> 的实例分配给类型 List< ??扩展Object> .但是您不能执行以下操作,因为您要将字符串添加到整数列表中.然后编译器将其捕获.

List<Integer> is a subtype of List<? extends Object> so you can assign an instance of List<Integer> to a type List<? extends Object>. But you can't do the following because you would be adding a String into a list of Integers. And the compiler catches it.

objs = ints; // okay
objs.add("abc"); // can't add String to list of ints

地图也是如此.

Map<String, ? extends Object> map;
Map<String, Integer> intMap = new HashMap<>();

map = intMap; // okay
map.put("abc", "abc");  //oops

编译器不知道您的地图所指的是什么,因此您无法向其添加对象.

The compiler has no idea what your map refers to so you can't add an object to it.

这篇关于为什么MAP使用通用通配符扩展对象不能容纳任何类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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