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
why i can't create a Map of String and generic object
提问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 Object
is 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 Object
is a supertype of everything, params
can be assigned be assigned a reference to both HashMap<String, Integer>
as well as HashMap<String, String>
, among many other things. A String
is not an Integer
nor is an Integer
a String
. The compiler has no way of knowing which params
may be, so it is not a valid operation to put anything in params
.
因为你不知道它是什么类型,?
所以你不能给它分配任何东西。由于Object
是所有事物的超类型,params
因此可以分配对两者HashMap<String, Integer>
以及的引用HashMap<String, String>
,等等。AString
不是 anInteger
也不是Integer
a String
。编译器无法知道哪个params
可能是,因此将任何内容放入params
.
If you want to be able to put <String, String>
in params
then 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.
回答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>