Java 泛型和有界类型

发布于 2024-11-14 07:03:02 字数 996 浏览 3 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感受沵的脚步 2024-11-21 07:03:03

让我们看看 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 方法的实现会更好。

谢谢,希望对你有帮助。

Let's look to signature of putAll

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

... and to error which you got:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文