Type mismatch when using Map.entrySet()

偶尔善良 提交于 2019-12-05 19:59:37
BarrySW19

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.

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

Simon G.

Imagine K and V are Number. The declaration does not link the types passed in with the map to those used in the entry set. Although we know it could never happen, if map is a Map<Integer,Integer> then the declaration allows s to be a Set<Entry<Double,Double>> as that still extends Number.

Therefore, if you are explicit that these types match, by writing this:

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

Your meaning is explicit, that the type of 's' will match exactly the types for 'map'. Hence it compiles happily.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!