Map< String,Class< ;?声明的问题扩展Serializable>> [英] Issue with declaration of Map<String,Class<? extends Serializable>>
问题描述
Java为我提供了<扩展类>
一种过滤可用于
的java类的方法,例如在此例中构建新的HashMap:
<我可以这样做:
地图< String ,?扩展Serializable> map1 = new HashMap< String,String>();
这是正确的,因为String实现了Serializable,所以编译器让我这么做。
但是当我尝试这样做时:
Map< String,GenericClass<扩展Serializable>> map2 = new HashMap< String,GenericClass< String>>();
因为它是GenericClass:
public class GenericClass< T>
{
。
。
。
}
编译器会抛出一个错误:
类型不匹配:无法从HashMap转换< String,GenericClass< String>>映射< String,GenericClass<?扩展Serializable>>
我想知道,发生了什么事情?
也许编译器无法检测到扩展类是泛型类型的一部分。 您需要使用以下内容:
地图< String,?扩展GenericClass< ;?扩展Serializable>> map2 =
new HashMap< String,GenericClass< String>>();
嵌套通配符与顶级通配符有很大不同 - 只有后者执行 通配符捕获 。因此, 有关嵌套通配符的更多信息,请参阅以下文章:多种通配符使Java编译器(和我!)非常困惑 Java provides me by I can do that: It is correct, because String implements Serializable, so the compiler let me do that. But when i try to do it: Being the GenericClass as it: The compiler throw an error saying: I would like to know, what is happen? Maybe the compiler cannot detect the extends class being part of a generic type. You would need to use the following: Nested wildcards are much different from top-level wildcards - only the latter perform wildcard capture. As a result, See this post for further information on nested wildcards: Multiple wildcards on a generic methods makes Java compiler (and me!) very confused 这篇关于Map< String,Class< ;?声明的问题扩展Serializable>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! HashMap< String,GenericClass< String>>
被认为不可转换为 Map< String,GenericClass<扩展Serializable>>
,因为 GenericClass< ;? extends Serializable>
是一个具体的类型参数(因为泛型
<? extends class>
a way of filtering the java classes that you can use to
build in this case the new HashMap, for example:Map<String,? extends Serializable> map1 = new HashMap<String,String>();
Map<String,GenericClass<? extends Serializable>> map2 = new HashMap<String, GenericClass<String>>();
public class GenericClass<T>
{
.
.
.
}
Type mismatch: cannot convert from HashMap<String,GenericClass<String>> to Map<String,GenericClass<? extends Serializable>>
Map<String, ? extends GenericClass<? extends Serializable>> map2 =
new HashMap<String, GenericClass<String>>();
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).