Reputation: 57284
I'm seeing some behavior I don't understand in the generic type of Map.entrySet. If I iterate through a typed map, I get expected types, e.g.
HashMap<A,B> map = new HashMap<>();
for(Map.Entry<A,B> e: map.entrySet(){ ... }
However, if I have an untyped map, the iterated type of the entry set is being reported as Object:
HashMap map = new HashMap();
a) for (Map.Entry e: map.entrySet(){ ... } // this will fail, e is being reported as "Object"
b) for (Object o: map.entrySet(){ ... } // this is compilable.
Shouldn't I be able to get an untyped entry as in statement a)? If I look at the hashmap implementation in the jvm, I see this:
c) public Set<Map.Entry<K,V>> entrySet() { ...
This behavior seems to imply that because the K,V is not specified in the second example, somehow the entire typing of the set contents in c) is omitted. Can anyone shed any light on this? Is this expected behavior?
Upvotes: 0
Views: 65
Reputation: 178263
The entrySet
method returns Set<K, V>
. However, when you use a raw type for your HashMap
, all generics in the type undergo type erasure, and the entrySet
method just returns a Set
. Iterating over a raw Set
will yield Object
s.
Upvotes: 3