why i can't create a Map of String and generic object
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();
whats wong with it..?
? 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
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
.
If you want to be able to put <String, String>
in params
then declare it as such. For example,
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 page and the one after it.
? 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
Map<String, TypeB>
精彩评论