不兼容的通用通配符捕获 [英] Incompatible generic wildcard captures

查看:125
本文介绍了不兼容的通用通配符捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的片段中:

  package test; 

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class WildcardsTest< K,V> {
private Iterator< Map.Entry< K,?扩展Collection< V>>>迭代器;
public WildcardsTest(Map< K,?extends Collection< V> map){
iterator = map.entrySet()。iterator();
/ *类型不匹配:无法从
转换Iterator< Map.Entry< K,capture#1-of?扩展Collection< V>>>到
迭代器< Map.Entry< K ,?扩展Collection< V>>> * /
}
}

分配不正确,完全匹配。



通过将Collection的类型指定为另一个泛型参数,我设计了一个肮脏的解决方法,如下所示:

  public class WildcardsTest< K,V,C扩展Collection< V>> {
private Iterator< Map.Entry< K,C>>迭代器;
public WildcardsTest(Map< K,C> map){
iterator = map.entrySet()。iterator();


但是 C 参数实际上是一种不关心类型,只会使API复杂化,是否有任何方法可以在维护类型安全性的同时摆脱它?




解决方案

像这样做,它会工作:

  private final Iterator <?>延伸
Map.Entry< K,?扩展Collection< V>>
>迭代器;

您仍然可以像这样使用迭代器:



($ iterator.hasNext()){
Entry< K,?扩展Collection< V>> entry = iterator.next();
Collection< V> value = entry.getValue();


$ / code $ / pre
$ b

仅供参考,请阅读获取和放置原则(最初来自 Java泛型和集合


in the following snippet:

package test;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class WildcardsTest<K, V> {
    private Iterator<Map.Entry<K, ? extends Collection<V>>> iterator;
    public WildcardsTest(Map<K, ? extends Collection<V>> map) {
        iterator = map.entrySet().iterator();
        /* Type mismatch: cannot convert from
           Iterator<Map.Entry<K,capture#1-of ? extends Collection<V>>> to
           Iterator<Map.Entry<K,? extends Collection<V>>> */
    }
}

The assignment is incorrect, although the types seem to match exactly.

I've devised a dirty workaround by specifying the type of the Collection as another generic parameter, like this:

public class WildcardsTest<K, V, C extends Collection<V>> {
    private Iterator<Map.Entry<K, C>> iterator;
    public WildcardsTest(Map<K, C> map) {
        iterator = map.entrySet().iterator();
    }
}

But that C parameter is really a "don't care" type that only complicates the API, is there any way to get rid of it while maintaining type safety?

Thanks.

解决方案

Do it like this and it will work:

private final Iterator<? extends
    Map.Entry<K, ? extends Collection<V>>
> iterator;

You can still use the iterator like this:

public void foo(){
    while(iterator.hasNext()){
        Entry<K, ? extends Collection<V>> entry = iterator.next();
        Collection<V> value = entry.getValue();
    }
}

For reference, read the get and put principle (originally from Java Generics and Collections)

这篇关于不兼容的通用通配符捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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