emarin
emarin

Reputation: 11

Put an object of the wrong type in a Map

Considering this piece of code, in which I have two maps, a Map<String, Integer> and a Map<String, String>. I assign the second one to an Object and cast this object to a Map so that I can putAll this map to the first one.

    Map<String, Integer> map = new HashMap<>();
    map.put("one", 1);
    Map<String, String> otherMap = new HashMap<>();
    otherMap.put("two", "two");

    Object obj = otherMap;

    map.putAll((Map<String,Integer>)obj);

    Assert.assertFalse(map.get("two") instanceof Integer);
    Assert.assertEquals("{one=1, two=two}", map.toString());

The first assert ensures that the second element of my Map is not a Integer, so how come the putAll did not fail ? The second assert is jus here to show that there is no apparent problem to this map. How can I make sure that the putAll method will fail, when the map is first assigned to an Object ?

Thanks

Upvotes: 1

Views: 490

Answers (2)

dnault
dnault

Reputation: 8889

You could, if you really wanted, use Collections.checkedMap to wrap the map and enforce the type-safety at runtime. There's an associated performance cost though.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198023

Generics are a compile-time feature, and are not enforced at runtime. Your code would compile with unchecked warnings telling you exactly this: that your code might behave unexpectedly.

To massively oversimplify, all Maps are treated as a Map<Object, Object> at runtime. (Not really, but sort of.)

Upvotes: 2

Related Questions