怎么会有ArrayList<Class<?>>
相同的擦除ArrayList<Object>
但不能转换为这种擦除的情况?
我的代码当前在两个Eclipse错误之间切换。
GenericExclusiveSelectionPanel transport =
new GenericExclusiveSelectionPanel(StringConstants.TRANSPORT,
(ArrayList<Object>)TransportManager.getInstance().getTransportTypes());
这表现了:
Cannot cast from ArrayList<Class<Transportable>> to ArrayList<Object>
但是,如果我删除演员表并创建一个构造函数:
GenericExclusiveSelectionPanel(String, ArrayList<Class<Transportable>>)
我得到的月食错误:
Erasure of method GenericExclusiveSelectionPanel(String,
ArrayList<Class<Transportable>>) is the same as another method in type
GenericExclusiveSelectionPanel
然后突出显示该构造函数(如下)作为冲突的构造函数。
GenericExclusiveSelectionPanel(String title, ArrayList<Object> arrayList)
如果我们先了解类型擦除相对于Java中的泛型意味着什么,那么更容易理解为什么会发生这种情况。在继续之前,请查看Oracle文档中的类型擦除。
现在您知道了类型擦除的含义,让我们看看Oracle文档对泛型要说的内容。
从文档中应该很清楚,泛型的主要目标是提供更严格的编译时间检查。如果编译器不对泛型进行强制转换检查,那将是一个很大的矛盾。为了便于讨论,假设假设允许以下语句:
List<String> strings = new ArrayList<String>();//1
strings.add("123");//2
List<Object> objects = strings;//3
objects.add(1);//4
如果编译器在步骤3中没有限制分配,则可以将an添加Integer
到String
对象列表中。如果编译器在第3步中不抱怨分配,那么泛型首先有什么好处,而这又使我们可以继续进行第4步?
同样,尽管ArrayList<Class<Transportable>>
和ArrayList<Object>
具有相同的擦除,但编译器正确地抱怨如上所述的分配问题。总之,使用泛型来限制这些强制转换与以相同的擦除来限制构造器/方法一样重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句