Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..?

like image 378
Saurabh Kumar Avatar asked Aug 05 '11 09:08

Saurabh Kumar


1 Answers

? 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.

like image 169
jw013 Avatar answered Oct 04 '22 21:10

jw013