Map< String,Class&lt ;?声明的问题扩展Serializable>> [英] Issue with declaration of Map<String,Class<? extends Serializable>>

查看:172
本文介绍了Map< String,Class&lt ;?声明的问题扩展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>>();

嵌套通配符与顶级通配符有很大不同 - 只有后者执行 通配符捕获 。因此, HashMap< String,GenericClass< String>> 被认为不可转换为 Map< String,GenericClass<扩展Serializable>> ,因为 GenericClass< ;? extends Serializable> 是一个具体的类型参数(因为泛型

有关嵌套通配符的更多信息,请参阅以下文章:多种通配符使Java编译器(和我!)非常困惑


Java provides me by <? extends class> a way of filtering the java classes that you can use to build in this case the new HashMap, for example:

I can do that:

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

It is correct, because String implements Serializable, so the compiler let me do that.

But when i try to do it:

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

Being the GenericClass as it:

public class GenericClass<T>
{
.
.
.
}

The compiler throw an error saying:

Type mismatch: cannot convert from HashMap<String,GenericClass<String>> to Map<String,GenericClass<? extends Serializable>>

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:

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&lt; String,Class&lt ;?声明的问题扩展Serializable&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆