Java泛型和有界类型

时间:2011-06-04 21:08:35

标签: java generics bounded-wildcard

我有一个ConcurrentMap的包装类,如下所示:

public MapWrapper<K, V> implements ConcurrentMap<K, V> {

    private final ConcurrentMap<K, V> wrappedMap;

    ...
    @Override
    public void putAll(Map<? extends K, ? extends V> map) {
        wrappedMap.putAll(map);  // <--- Gives compilation error
    }
    ...
}

标记的行会触发以下编译错误:

method putAll in interface java.util.Map<K,V> cannot be applied to given types;
required: java.util.Map<? extends capture#5 of ? extends K,? extends capture#6 of ?
    extends V>
found: java.util.Map<capture#7 of ? extends K,capture#8 of ? extends V>
reason: actual argument java.util.Map<capture#7 of ? extends K,capture#8 of ? extends V> 
    cannot be converted to java.util.Map<? extends capture#5 of ? extends K,? extends 
    capture#6 of ? extends V> by method invocation conversion

我怀疑无界的通配符是罪魁祸首但我无法更改方法签名,因为它是从ConcurrentMap接口继承的。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

让我们看看putAll的签名

public void putAll(Map<? extends K, ? extends V> m)

...以及你得到的错误:

cannot be converted to java.util.Map<? extends capture#5 of ? extends K,? extends 

所以你不能这样做的原因,它限制了Java中继承树的合并。

可能最好编写自己的putAll方法实现。

谢谢,希望它会对你有帮助。