2011-06-04 132 views
2

我有这样的ConcurrentMap的包装类如下:Java泛型和界类型

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

你正在使用什么样的编译器(同样,IDE可能有它自己的,就像Eclipse一样)?我设法在Eclipse中编译并使用javac(1.6);你也可以尝试转换wrappedMap.putAll((Map )m); – 2011-06-04 21:20:31

+1

只是试图重现你有的代码和...一切工作正常。我创建了一个模拟'MapWrapper '并实例化'。然后用'HashMap 调用'putAll'方法,一切正常。 (使用eclipse和Java 1.6) – 2011-06-04 21:29:22

+0

谢谢亚瑟,我发现了错误。事情是,包装图不是一个真正的ConcurrentMap,而是一个实现该接口的类。我在代码中混合了两种不同的东西,但由于涉及到泛型,错误消息确实没有太大的帮助。 – teto 2011-06-04 21:51:30

回答

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方法的实现。

谢谢,希望它能帮助你。

+0

我不确定“继承树合并的限制”是什么意思,但如果您阅读了注释,则OP发现错误是由于一个无关的问题造成的。 – 2012-03-31 21:09:38