java 为什么我不能创建字符串和通用对象的映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6954509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:00:55  来源:igfitidea点击:

why i can't create a Map of String and generic object

javagenericsmaphashmap

提问by Saurabh Kumar

I am trying to do something like this

我正在尝试做这样的事情

  final Map<String, ? extends Object> params = new HashMap<String, ? extends Object>();

but java compiler complaining about that "cannot instantiate the type HashMap();

但是java编译器抱怨“无法实例化HashMap()类型;

whats wong with it..?

怎么了..?

回答by jw013

? extends Objectis a wildcard. It stands for "some unknown type, and the only thing we know about it is it's a subtype of Object". It's fine in the declaration but you can't instantiate it because it's not an actual type. Try

? extends Object是通配符。它代表“某种未知类型,我们唯一知道的是它是”的子类型Object。它在声明中很好,但你不能实例化它,因为它不是一个实际的类型。尝试

final Map<String, ? extends Object> params = new HashMap<String, Object>();

Because you do not know what type the ?is you can't assign anything to it. Since Objectis a supertype of everything, paramscan be assigned be assigned a reference to both HashMap<String, Integer>as well as HashMap<String, String>, among many other things. A Stringis not an Integernor is an Integera String. The compiler has no way of knowing which paramsmay be, so it is not a valid operation to put anything in params.

因为你不知道它是什么类型,?所以你不能给它分配任何东西。由于Object是所有事物的超类型,params因此可以分配对两者HashMap<String, Integer>以及的引用HashMap<String, String>,等等。AString不是 anInteger也不是Integera String。编译器无法知道哪个params可能是,因此将任何内容放入params.

If you want to be able to put <String, String>in paramsthen declare it as such. For example,

如果您希望能够放入<String, String>params则将其声明为这样。例如,

final Map<String, Object> params = new HashMap<String, Object>();
params.put("a", "blah");

For a good intro on the subject, take a look at the Java Language tutorial on generics, esp. this pageand the one after it.

有关该主题的良好介绍,请查看有关泛型的 Java 语言教程,尤其是。这一页和它之后的一页

回答by Swagatika

? extends Object

does not evaluate to any Type. so you can not mention like that. 1. If you want AnyType extends Object, then why do'nt you simply pass Object. as anyType that extends Object is also an Object. and by default every Java class Type extends Object. 2. If you want specifically TypeA extends TypeB, then you can do like

不计算为任何类型。所以你不能这样提。1. 如果你想要 AnyType 扩展 Object,那你为什么不简单地传递 Object。因为扩展 Object 的 anyType 也是一个 Object。默认情况下,每个 Java 类 Type 都扩展了 Object。2.如果你想特别TypeA扩展TypeB,那么你可以这样做

Map<String, TypeB>