31

I have the following JAVA method implemented due a interface:

public String importDocument(ImportSource source, Map<String, ? extends Object> paramMap);

When i try to do following, i get an compile warning. Snippet:

paramMap.put("Key", "Value");

Error:

The method put(String, capture#1-of ? extends Object) in the type Map is not applicable for the arguments (String, String)

Why?

Emaborsa
  • 2,360
  • 4
  • 28
  • 50

1 Answers1

32
? extends Object

You are using generic wildcard. You cannot perform add operation as class type is not determinate. You cannot add/put anything(except null).

For more details on using wildcard you can refer oracle docs.

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Does it mean, that if i need to add a value to the params, i must create a new map with all values and use this instead? – Emaborsa Jan 10 '14 at 10:01
  • 1
    If you want to add params then dont use wildcard use `Map` instead. – Aniket Thakur Jan 10 '14 at 10:04
  • 1
    Anyway `? extends Object` makes no sense as every class is eligible as the argument. – Aniket Thakur Jan 10 '14 at 10:04
  • 1
    I can't change it, is a well defined interface which i must use as it is. However i don't really get it. What is the difference between `Map` and `Map` – Emaborsa Jan 10 '14 at 10:10
  • 4
    @Emaborsa you may want to see this [question](http://stackoverflow.com/questions/17834145/whats-the-use-of-saying-extends-someobject-instead-of-someobject/17834223#17834223). – Aniket Thakur Jan 10 '14 at 10:14
  • Or `` would also solve it (if `T` is a type param for the function). – rlegendi Jan 10 '14 at 13:08