Cannot cast from Map<String,Object> to Map<String,List<Map<String,String>>>
casting, generics, java
Solution
As long as you're sure that the returned map will only contain values of type `List<Map<String, String>>`, then you need to use a double cast:
Map<String, Object> map = this.getMethod().execute(mp);
@SuppressWarnings("unchecked") //thoroughly explain why it's okay here
Map<String, List<Map<String, String>>> mapWithNarrowedTypes =
(Map<String, List<Map<String, String>>>)(Map<?, ?>)map;
return mapWithNarrowedTypes;
Problem
I am upgrading the following code: ``` return this.getMethod().execute(mp); ``` Where the execute method has signature: ``` public Map<String,Object> execute(Object mp) ``` I have code that expects the return of the method to be `Map<String, List<Map<String, String>>>`, but the compiler is choking on the conversion. So can I / how do I get this to cast properly? And is there any change between Java 5 and 6 that would make this now a compile time issue?