Getting 'Type mismatch: cannot convert from ArrayList<HashMap<String,String>> to List<Map<String,String>>' while instantiating a list of maps

DockYard :
List<Map<String, String>> recordMapList = new ArrayList<HashMap<String,String>>();

The above line gives the error: Type mismatch: cannot convert from ArrayList> to List>

But the issue goes away if use HashMap instead of Map in the left hand side. Could someone tell me why this happens. I need to have the left hand side to contain Map as I might be using the same variable to assign LinkedHashMap in the righ side like,

List<Map<String, String>> recordMapList = new ArrayList<LinkedHashMap <String,String>>();

Please help.

Kevin Cruijssen :

Although ArrayList is a sub class of List, and Map is a subclass of HashMap, an List<Map> is NOT a subclass of List<HashMap>. Similarly you cannot cast a List<HashMap> to a List<Map>. If we could, it would mean we could add let's say a TreeMap to our List<Map>, and then cast it to a List<HashMap>, thus violating the original contract of the List<HashMap>.

Personally I would just use a diamond operator (Java 7+) if the recordMapList-instance is immediately created:

List<Map<String, String>> recordMapList = new ArrayList<>();

And if it's created elsewhere only the List can be an ArrayList, but the rest would be the same. (NOTE: You could of course still use the diamond operator here as well, but if creating the instance and the actual field are separated, I personally prefer to use the types so it's instantly clear what type goes into the list, without jumping to the actual field in the code.)

List<Map<String, String>> recordMapList;
...
recordMapList = new ArrayList<Map<String, String>>();

In both cases you can add your HashMap<String, String> instances to the recordMapList.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76363&siteId=1