Java - Cast a Map

I think it's a good idea to explain why the simple solution doesn't work and why you never, ever should use this.

Assume you could cast List<Object> to List<String> (the same applies to Map, just a simpler interface). What would you expect to happen from the following code:

List<Object> m = Something;
m.add("Looks good.");
m.add(42);
List<String> s = (List<String>)m; // uhuh, no we don't want that.
String myString = s.get(1); // huh exception here.

Now you CAN hack it indeed using Bohemians/Chris solution, but you basically destroy Java's type system. DON'T DO THAT. You don't want a List<String> to contain an Integer! Have fun debugging that later on - the additional code of looping through all variables will avoid lots of headaches and hardly is a performance problem.

If there's a reason to declare the Map as taking an Object instead of a String someone may add any object to it - usually you should be able to avoid this with a better generic.


The actual answer is:

Map<Object,Object> valueMap = ...;
@SuppressWarnings("unchecked")
Map<String,String> targetMap = (Map)valueMap;

Tags:

Java

Casting

Map