Can somebody explain me why this
Map<String, List<String>> foo = new HashMap<String, LinkedList<String>>();
generates a type mismatch error ?
Type mismatch: cannot convert from HashMap< String,LinkedList< String>> to Iterators.Map< String,List< String>>
Hashmap implements the Map interface, and LinkedList implements the List interface. Moreover, this
List<String> foo = new LinkedList<String>();
works…
Thanks
Fix this like the following:
Map<String, List<String>> result = new HashMap<String, List<String>>();Pay attention that I changed
LinkedListtoListin the right side of your assignment.You are right that LinkedList implements List. But I think that explanation of this error is not in definition of List but in definition of interface
Map<K,V>.The left side of your expression says that you want to create Map of String and List, i.e.
Vis “replaced” by List. Right side uses LinkedList. Although LinkedList implements List it does not work because the definition of Map is not something likeMap<K, V extends List>, so compiler requires exact match.I am not sure that my description is strict enough, but anyway this is the way to right generics. Really, when you create map of list you do not care about the implementation of List, therefore say
HashMap<String, List<String>>. Only when you create instance of List care about its implementation. This will allow you to change the implementation if future without modification of other code.