Anand
Anand

Reputation: 12142

Typecast Map<String, String> to Map<Object, Object>

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.

Upvotes: 1

Views: 6823

Answers (4)

falsarella
falsarella

Reputation: 12437

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.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691655

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>.

Upvotes: 4

Reddy
Reddy

Reputation: 8911

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

OR

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

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can use

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

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

Upvotes: 7

Related Questions