Issue with declaration of Map<String,Class<? extends Serializable>>

泄露秘密 提交于 2019-12-03 15:36:00
Paul Bellora

You would need to use the following:

Map<String, ? extends GenericClass<? extends Serializable>> map2 =
        new HashMap<String, GenericClass<String>>();

Nested wildcards are much different from top-level wildcards - only the latter perform wildcard capture. As a result, HashMap<String, GenericClass<String>> is considered inconvertible to Map<String, GenericClass<? extends Serializable>>, because GenericClass<? extends Serializable> is a concrete type argument (and because generics aren't covariant).

See this post for further information on nested wildcards: Multiple wildcards on a generic methods makes Java compiler (and me!) very confused

Map<String,? extends Serializable> map1 = new HashMap<String,String>();

map1 contains an unbounded V that only requires an unknown of Serializable's. Hence it cannot find a generified object to bound this to, except for null.

Map<String,GenericClass<? extends Serializable>> map2 = new HashMap<String, GenericClass<String>>();

The map2 is bounded by a type K (in this case String) and V (Class<? exends Serializable). That's how the Java compiler sees the bounds.

In essence, you cannot put anything in map1 except a null as you will only see map1.put(String key, null value) //Compiler is asking WTF here. Whereas, map2 will, essentially "render" as map2.put(String key, Class<? extends Serializable> value); //Much better....

Because of the bound V in map2, the signature must be the same in its declaration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!