0

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.

3
  • If you are sure that the key of pMap is an integer, then you can use the following type for pMap....Map<Integer, Map<Object, Object>> pMap Commented Nov 1, 2012 at 6:59
  • Well that's the problem, sometimes I would use String instead of Integer as a key. Commented Nov 1, 2012 at 7:02
  • 1
    Then you can declare the Key of 'map' also as Object, and perform the casting while operating on the key or the value. Commented Nov 1, 2012 at 7:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, thank you. I guess I have to find another elegant way to make it as generic as possible.
0

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.

1 Comment

I tried with ? instead of Object but it's the same, the cast is forbidden. What I do is casting trough an iterator, I cannot directly cast the Map. Thank you for your answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.