Reputation: 231
I'm trying to cast a Map like this :
Map<Integer, Map<String, String>> map =
(HashMap<Integer, Map<String, String>>) pMap;
pMap is typed :
Map<Object, Map<Object, Object>> pMap
Unfortunately it doesn't work and I'm curious to know why, and also if it's possible to avoid the problem.
Upvotes: 0
Views: 212
Reputation: 231
So, here is what I did to avoid this problem :
I typed my Map like this :
Map<? super Object, ? super Object>
And it works, I can put whatever I want inside this Map. It can be :
Map<String, String>
or :
Map<Integer, Map<String, String>>
etc. It's the more flexible way I found. The only constraint is to cast the Map when I operate on the map (through Iterator
or with keySet
).
Hope it could help someone.
Upvotes: 0
Reputation: 2238
I am not much familiar with generic class but can you try Map<?, Map> map after replacing Integer by ? It will case your Integer easily and as you wrote above that this key can be string too so I hope it will work for you.
Upvotes: 0
Reputation: 46209
This is because even though Integer
is a subtype of Object
, Map<Integer, Integer>
is not a subtype of Map<Object, Object>
.
You simply cannot cast it that way.
This is explained further in the Java Tutorials.
Upvotes: 3