Java 泛型和有界类型
我有一个 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 接口继承的。有什么想法吗?
I have a wrapper class for ConcurrentMap like the following:
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
}
...
}
The marked line triggers the following 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
I suspect the unbounded wildcards are the culprit but I can't change the method signature since it is inherited from the ConcurrentMap interface. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否看过:
有界通配符和类型参数之间有什么区别?
Have you seen:
What is the difference between bounded wildcard and type parameters?
让我们看看 putAll
... 的签名以及您得到的错误:
所以您不能这样做的原因是,这是 Java 中继承树合并的限制。
也许,编写自己的 putAll 方法的实现会更好。
谢谢,希望对你有帮助。
Let's look to signature of putAll
... and to error which you got:
So reason why you can't do it, it's restriction of merging of inheritance tree in Java.
Probably, will be better to write your own implementation of putAll method.
Thanks, hope it will help you.