1

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.

1 Answer 1

2

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>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.