Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics and upcasting

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

like image 300
Simon Avatar asked Aug 22 '11 05:08

Simon


1 Answers

Because a Map<String, List<String>> allows you to put an ArrayList<String> into it, but doing so would violate the type integrity of a HashMap<String, LinkedList<String>>.

Either declare your HashMap as a HashMap<String, List<String>> or your variable as a Map<String, LinkedList<String>> or Map<String, ? extends List<String>>.

Edit

The more immediate problem is that you have imported the wrong Map class (something called Iterators.Map) or you have another class (or inner class rather) called Map in the same package as this code. You want to import java.util.Map.

like image 125
Mark Peters Avatar answered Oct 11 '22 06:10

Mark Peters