Java generics How to accept any derived type in generic parameter

Viewed 2221

In The below 2 lines of code

HashMap<Integer, ?extends Collection<String>> map=
                                           new HashMap<Integer, TreeSet<String>>();

map.put(1,new TreeSet<String>());

Line 2 :The method put(Integer, capture#1-of ? extends Collection) in the type HashMap> is not applicable for the arguments (int, TreeSet)

Line 1: this has no error.

Why is the same generic type (TreeSet< String >) allowed in Line 1 but not allowed in Line 2?

Edit : With super instead of extends ,why is the following is NOT allowed.

HashMap<Integer, ?super Collection<String>> map=new HashMap(<Integer, TreeSet<String>>());

but

HashMap<Integer, ?super Collection<String>> map=new HashMap();
map.put(1,new TreeSet<String>());

is allowed

4 Answers
Related