Java Casting Problem

castinggenericsjava

Why isn't a Map<String,List<SomeBean>> castable to Map<String,List<?>>?

What I'm doing now is this:

Map<String, List<SomeBean>> fromMap = new LinkedHashMap<String, List<SomeBean>>();

/* filling in data to fromMap here */

Map<String,List<?>> toMap = new LinkedHashMap<String, List<?>>();
for (String key : fromMap.keySet()) {
    toMap.put(key, fromMap.get(key));
}

In my opinion there should be a way around this manual transformation, but I can't figure out how. Any Ideas?

Best Answer

The cast is invalid because in Map<String,List<?>> you can put List<String> and List<WhatEver>, but not in Map<String, List<SomeBean>>.

For instance:

    //List<SomeBean> are ok in both lists
    fromMap.put("key", new ArrayList<SomeBean>());
    toMap.put("key", new ArrayList<SomeBean>());

    //List<String> are ok in Map<String,List<?>>, not in Map<String, List<SomeBean>>
    fromMap.put("key", new ArrayList<String>()); //DOES NOT COMPILE
    toMap.put("key", new ArrayList<String>());

To simplify your code, you may use the appropriate constructor to simplify your code:

    Map<String, List<SomeBean>> fromMap = new LinkedHashMap<String, List<SomeBean>>();
    Map<String,List<?>> toMap = new LinkedHashMap<String, List<?>>(fromMap);