1
Map<String, String> fieldAttributes = new HashMap<String, String>();

fieldAttributes.put("a", "48");
fieldAttributes.put("b", "");
fieldAttributes.put("c", "4224");

Now I need to cast Map<String, String> to Map<Object, Object>

How can I do this. I tried ? extends Object but not sure how to use it.

4
  • you can directly use Map<Object, Object> right ??? Commented Jan 12, 2012 at 11:22
  • Why Map<Object,Object>? after all String is Object Commented Jan 12, 2012 at 11:22
  • 1
    @AVD because i need to feed the object to a function which will take it as Map<Object,Object> only. Commented Jan 12, 2012 at 11:27
  • Are you sure you want to do this? Map<Object,Object> is neither a subtype nor a supertype of Map<String,String>. Try Map<?,?> instead - it's a supertype of both Map<String,String> and Map<Object,Object>, so it might be what you want. Is the function that requires Map<Object,Object> something you can change? Commented Jan 12, 2012 at 11:29

4 Answers 4

7

You can use

Map<Object, Object> properties = (Map) fieldAttributes;

The compiler gives you an appropriate warning, but it compiles.

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

Comments

4

You can't. A Map<String, String> is not a Map<Object, Object>. If it was, you could do

Map<String, String> map = new HashMap<String, String>();
Map<Object, Object> map2 = (Map<Object, Object>) map;
map2.put(Integer.valueOf(2), new Object());

which would break the type safety that generics bring.

So, you'll indeed have to use a raw map, or use a Map<? extends Object, ? extends Object>.

Comments

1
Map<? extends Object, ? extends Object> genMap = fieldAttributes;

OR

Map<Object, Object> gMap = (Map)fieldAttributes;

2 Comments

Or just Map<?,?>. The "extends Object" is kind of implied.
Yes, Map<?, ?> can be used as every class extends Object.
0

Instead of casting, you can just use Object instead of String:

Map<Object, Object> fieldAttributes = new HashMap<Object, Object>();
fieldAttributes.put("a", "48");
fieldAttributes.put("b", "");
fieldAttributes.put("c", "4224");

When iterating the Map, you can use Object's .toString() method to transform.

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.