Question

The code getting me confusing:

 Collection<? extends Map<String, String>> a = 
                       new ArrayList<SortedMap<String, String>>();
 SortedMap<String, String> b = new TreeMap<String, String>();
 b.put("1","a");

Error:

 a.add(b);

The method add(capture#2-of ? extends Map) in the type Collection> is not applicable for the arguments (SortedMap) Why? SortedMap extends Map and TreeMap is a class that implements SortedMap.

Was it helpful?

Solution

This means

 Collection<? extends Map<String, String>> a ;

The elements of a are an unknown class which extends a Map. You means when you get a value out it is a Map, but you cannot say which map would be valid to add to the collection.

For example, a doesn't know the class which extends Map so it cannot allow any sub-class as it cannot know which is valid.

List<HashMap<String, String>> listOfMap = new ArrayList<>();
Collection<? extends Map<String, String>> a = listOfMap;
SortedMap<String, String> b = new TreeMap<String, String>();
b.put("1", "a");
a.add(b); // produces an error  as it should.

If you change a to be

Collection<SortedMap<String, String>> a = new ArrayList<SortedMap<String, String>>();

It is fine to add b as it is this type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top