使用Map.entrySet()时类型不匹配 [英] Type mismatch when using Map.entrySet()

查看:553
本文介绍了使用Map.entrySet()时类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:在下面的代码中,方法 foo 编译时,方法 bar 赢得'吨。在方法调用 entrySet (代码中指出)编译器说:

I have the following situation: In the code below, the method foo compiles while the method bar won't. At the method call entrySet (indicated in the code) the compiler says:

Type mismatch: cannot convert 
from Set<Map.Entry<capture#1-of ? extends K,capture#2-of ? extends V>> 
to Set<Map.Entry<? extends K,? extends V>>

有趣的是,Eclipse的quickfix建议

Interestingly, the quickfix of Eclipse proposes to

Change type of 's' to Set<Entry<? extends K, ? extends V>>

只能更改代码,因为quickfix忽略了自己的提案并更改了<$ c的类型$ c> s 到设置<?>

which only changes the code because the quickfix is ignoring its own proposal and changing the type of s to Set<?> instead.

我正在使用JDK1.8.0_51和Eclipse 4.4.0。也许它与通配符或捕获有关系?任何帮助或建议将不胜感激。感谢提前!

I am using JDK1.8.0_51 and Eclipse 4.4.0. Maybe it has something to do with the wildcards or captures? Any help or advice would be appreciated. Thanks in advance!

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MyClass<K, V> {
    public void foo(Set<Entry<? extends K, ? extends V>> set) {
        Iterator<Entry<? extends K, ? extends V>> i = set.iterator();
    }

    public void bar(Map<? extends K, ? extends V> map) {
        Set<Entry<? extends K, ? extends V>> s = map.entrySet();
                                                 ^^^^^^^^^^^^^^
    }
}


推荐答案

简单的答案是,如果您以您的问题的方式声明了Set,则可能会添加不符合该条目的条目到传递给方法的对象的类型。 Java不保留足够的信息来检查Set定义中的?extends K与方法参数中的?extends K相同。

The short answer is that, if you declared the Set in the way you have in your question, it would be possible to add entries to it which did not conform to the types of the objects passed in to the method. Java does not retain sufficient information to check that the "? extends K" in the Set definition is the same as the "? extends K" in the method parameter.

避免此Java要求您将作业声明为:

To avoid this Java requires you to declare the assignment as:

Set<? extends Map.Entry<? extends K,? extends V>> s = map.entrySet();

...你会发现你不能将自己的条目添加到这个集合 - 至少不是没有做很多不好的投票,这将产生很多警告。

... and you will find you cannot add your own entries into this set - at least, not without doing a lot of bad casting which will generate a lot of warnings.

如上所述,这个问题更详细地讨论了这个主题:条目集中的通用迭代器

As someone mentioned above, this question covers the subject in more detail: Generic Iterator on Entry Set

这篇关于使用Map.entrySet()时类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆