I have a Map<K, V>
and want to cast it to a Map<K, U>
where V
extends U
. Example: I want to go from Map<String, String>
to Map<String, Object>
. This problem exists with all kinds of collections.
This question already has an answer with a "hacky" solution and one that explains why casting generic types is generally a bad idea. But let's revisit the example from the answer from Voo:
List<String> m = Something;
m.add("Looks good.");
m.add("42");
List<Object> s = (List<Object>)m; // (1) does not compile
List<Object> t = (List)m; // (2) compiles with warnings
Object myObject = s.get(1);
A few questions about this example:
- Why does this (1) not compile? Is a way to make it compile other than the hack (2)?
- What could possibly go wrong when casting a
List<String>
to aList<Object>
since all Strings are objects?
My concrete problem:
I have got a Map<Integer, Map<Vector2i, MyClass> > map = ...
that contains a map for each level. The map on level 0 is of type Map<Vector2i, MySubClass> special = ...
. I want now special
to be part of map
for the key 0 so that accesses to the map
for key 0 can be treated as a normal Map<Vector2i, MyClass>
object.
The situation is read-only, meaning that writing to map
and special
happens separatedly.