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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With