2

我有一个 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 接口继承的。有任何想法吗?

4

2 回答 2

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 方法实现会更好。

谢谢,希望对你有帮助。

于 2012-03-31T19:39:44.493 回答
0

你见过:

有界通配符和类型参数有什么区别?

于 2011-06-04T21:13:21.363 回答