13

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

Jonas
  • 121,568
  • 97
  • 310
  • 388
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

2 Answers2

17

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

jw013
  • 1,718
  • 17
  • 22
  • but then what if i want to store – Saurabh Kumar Aug 05 '11 at 10:02
  • @Saurabh That will work fine, since the String class (like almost all classes) is a subclass of Object. This implementation works fine if you want to store an instance of absolutely any class in your HashMap. Some details on what you're actually trying to achieve would probably help us to determine whether or not this is the correct approach. – Anthony Grist Aug 05 '11 at 10:13
  • I'd be interested to hear why `final Map params = Collections.emptyMap();` doesn't work. Throws `UnsupportedOperationException` when trying to put `` – Snekse Nov 14 '11 at 21:52
  • Also, IntelliJ (in Java 14) suggests doing `Map` instead of `Map`... – Erk Dec 12 '20 at 13:17
0
? 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>
Swagatika
  • 3,376
  • 6
  • 30
  • 39