javagenericsdata-structureshashmaplinkedhashmap

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


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.


Solution

  • Although ArrayList is a sub class of List, and HashMap is a subclass of Map, an List<HashMap> is NOT a subclass of List<Map>. 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.