开发者

Java generics and bounded types

开发者 https://www.devze.com 2023-03-10 05:07 出处:网络
I have a wrapper class for ConcurrentMap like the following: public MapWrapper<K, V> implements ConcurrentMap<K, V> {

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 unbo开发者_JAVA技巧unded wildcards are the culprit but I can't change the method signature since it is inherited from the ConcurrentMap interface. Any ideas?


Have you seen:

What is the difference between bounded wildcard and type parameters?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消