JaneDoe
JaneDoe

Reputation: 107

Generic programming : error when trying to put values in an EnumMap

I am using Java generic programming for creating an HashMap:

 Map< String, ? super TreeSet< MyObject>> myMap = new HashMap< String, TreeSet< MyObject>>();

However when I try to add something in myMap, I get an error.

Set< MyObject> mySet = new TreeSet< MyObject>();
myMap.put("toto", mySet);

The error is:

put(String, capture< ? super java.util.TreeSet< MyObject>>) in Map cannot be applied to (String, java.util.Set< MyObject>)

Any help would be much appreciated.

Upvotes: 1

Views: 60

Answers (1)

M A
M A

Reputation: 72884

mySet is declared to be of type Set while the map can only contain TreeSets in the values. The compiler cannot guarantee that mySet, which is to be added, is not a HashSet, which can lead to a runtime exception. That's why it signals a compilation error.

You should program to the interface when declaring TreeSet as a type argument. In other words, you should use Set instead:

Map<String, ? super Set<MyObject>> myMap = new HashMap<String, Set<MyObject>>();

Unless you're certain that only TreeSets are always used, in which case you can change the type of mySet to TreeSet:

// or
TreeSet<MyObject> mySet = new TreeSet<MyObject>();

Upvotes: 2

Related Questions