how to instantiate set of map in java correctly?

I want to have a Set < Map <Character, Integer> > instance. However I can't instantiate it with new HashSet < HashMap<Character, Integer> >.

I have to either change it to

Set<HashMap<Character, Integer>> v = new HashSet<HashMap<Character, Integer>>();

or

Set<Map<Character, Integer>> v = new HashSet<Map<Character, Integer>>();   // I prefer this one

Could anyone tell me why Java can't convert HashSet<HashMap<Character, Integer>> to Set<Map<Character, Integer>>?

Jon Skeet
people
quotationmark

It's simpler to show you an equivalent situation - let's use Object and String in the place of Map<Character, Integer> and HashMap<Character, Integer>.

Suppose we could write Set<Object> set = new HashSet<String>();. Then this code would have to be valid:

HashSet<String> strings = new HashSet<String>();
HashSet<Object> objects = strings;
objects.add(new Object()); // Not a string!

String firstString = strings.iterator().next(); // Bang!

Do you see what's going wrong here? A set of strings isn't a set of objects, because you can add any object to a set of objects, whereas a set of strings can only contain strings.

Once you've got your head round that, port it back to your more complex situation: a Set<HashMap<Character, Integer>> can only contain HashMap<Character, Integer> elements... whereas with a Set<Map<Character, Integer>> you could add any kind of Map<Character, Integer>. So they're not compatible.

people

See more on this question at Stackoverflow