First, I tried to use
Map<Integer, Set<Integer>> map = new HashMap<Integer, HashSet<Integer>>();
, but it did not compile because no casting is available.
Then I tried
Map<Integer, ? extends Set<Integer>> map = new HashMap<Integer, HashSet<Integer>>();
. It seemed to work, but when I tried to call
map.put(i, new HashSet<Integer>());
, it turned out to be a failure due to uncompatibility.
How can I solve the problem?
You can simply do this:
When you retrieve the value from the map, then it will be of type
Set<Integer>, but that shouldn’t make any difference as per your expectation. But if you want to retrieve onlyHashSet<Integer>then your map definition should be