简体   繁体   English

奇怪的Java类型行为

[英]Odd java type behavior

I'm seeing some behavior I don't understand in the generic type of Map.entrySet. 我在Map.entrySet的通用类型中看到了一些我不了解的行为。 If I iterate through a typed map, I get expected types, eg 如果我遍历一个类型化的映射,我会得到预期的类型,例如

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: 但是,如果我有一个无类型的映射,则该条目集的迭代类型将报告为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)? 我不应该能够像语句a)中那样获得未键入的条目吗? If I look at the hashmap implementation in the jvm, I see this: 如果我看一下jvm中的hashmap实现,则会看到以下内容:

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. 此行为似乎暗示着,因为在第二个示例中未指定K,V,因此某种程度上省略了c)中设置内容的整个键入。 Can anyone shed any light on this? 谁能对此有所启示? Is this expected behavior? 这是预期的行为吗?

The entrySet method returns Set<K, V> . entrySet方法返回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 . 但是,当您为HashMap使用原始类型时,该类型中的所有泛型都会进行类型擦除,而entrySet方法仅返回Set Iterating over a raw Set will yield Object s. 遍历原始Set将产生Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM