gpt4 book ai didi

java - 遍历 map 条目集

转载 作者:太空狗 更新时间:2023-10-29 22:50:41 24 4
gpt4 key购买 nike

我需要遍历一个我不知道其参数化类型的映射的条目集。

当遍历这样的条目集时,为什么不编译?

public void myMethod(Map anyMap) {
for(Entry entry : anyMap.entrySet()) {
...
}
}

但是这个编译:

public void myMethod(Map anyMap) {
Set<Entry> entries = anyMap.entrySet();
for(Entry entry : entries) {
...
}
}

这也可以编译(我不能使用这个,因为我不知道 map 的类型):

public void myMethod(Map<String, String> stringMap) {
for(Entry<String,String> entry : stringMap.entrySet()) {
...
}
}

最佳答案

您在第一个错误中遇到的错误是:

Type mismatch: cannot convert from element type Object to Map.Entry

这是因为编译器转换了你的 FOR-IN 循环:

for (Entry entry : anyMap.entrySet()) {
}

收件人:

for (Iterator i = anyMap.entrySet().iterator(); i.hasNext();) {
Entry e = i.next(); // not allowed
}

您的第二个示例有效,但只能通过作弊!您正在进行未经检查的转换以获得 Set 回到 Set<Entry> .

Set<Entry> entries = anyMap.entrySet(); // you get a compiler warning here
for (Entry entry : entries) {
}

变成:

Set<Entry> entries = anyMap.entrySet();
for (Iterator<Entry> i = entries.iterator(); i.hasNext(); ) {
Entry e = (Entry) i.next(); // allowed
}

更新

如评论中所述,类型信息在两个示例中都丢失了:因为编译器的原始类型删除规则。

为了提供向后兼容性,原始类型实例的所有 方法都被替换为它们的删除 对应物。所以,因为你的 Map是原始类型,它全部被删除。包括它的Set<Map.Entry<K, V>> entrySet();方法:您的原始类型实例将被迫使用已删除的版本:Set entrySet() .

关于java - 遍历 map 条目集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14933648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com