0

I have seen several questions on this topic, but still can't figure out how to solve this problem. I define and initialize my variable as:

Queue<? extends Map<String, String>> q = new LinkedList<HashMap<String, String>>();

And it compiles. But then:

Map<String, String> m = new HashMap<String, String>();
m.put("foo", "bar"); 
q.add(m);

reports a compilation error: no suitable method found for add(Map<String,String>).

EDIT:

I think this is different to Can't add value to the Java collection with wildcard generic type, because the generics are not nested in that question.

Furthermore, the accepted answer teaches that the specific implementation of a template class can be omited in some declarations. You won't find this teaching on the question marked as duplicate of.

Community
  • 1
  • 1
clapas
  • 1,768
  • 3
  • 16
  • 29

1 Answers1

0

? means "unknown type". Since the type is unknown, the compiler can't guarantee that the type is Map<String, String>. So it refuses to let you add anything in the queue, since it could compromise its type-safety.

Your variable should be declared as

Queue<Map<String, String>> q = new LinkedList<Map<String, String>>();

or simply, if you're on Java 7 or later

Queue<Map<String, String>> q = new LinkedList<>();
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Awesome! Of course! I didn't know I could postpone the declaration of the implementation of the map at this point. Thank you. – clapas Oct 05 '14 at 13:50