怎么会是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>>)
我收到 Eclipse 错误:
Erasure of method GenericExclusiveSelectionPanel(String,
ArrayList<Class<Transportable>>) is the same as another method in type
GenericExclusiveSelectionPanel
然后它会突出显示构造函数(如下)作为冲突的构造函数。
GenericExclusiveSelectionPanel(String title, ArrayList<Object> arrayList)
最佳答案
如果我们首先了解 Java 中的类型删除对于泛型的含义,就会更容易理解为什么会发生这种情况。看看type erasure在继续之前先阅读 Oracle 文档。
现在您已经了解了类型删除的含义,让我们看看 Oracle 文档中关于 generics 的说明。 。
从文档中可以清楚地看出,泛型的主要目标是提供更严格的编译时检查。如果编译器不强制检查泛型的强制转换,那将是相当矛盾的。为了便于讨论,假设允许以下语句:
List<String> strings = new ArrayList<String>();//1
strings.add("123");//2
List<Object> objects = strings;//3
objects.add(1);//4
如果编译器在步骤 3 中没有限制赋值,您将能够添加 Integer
到 String
的列表对象。如果编译器没有提示第 3 步的赋值,从而允许我们继续执行第 4 步,那么泛型首先有什么好处?
同样,而 ArrayList<Class<Transportable>>
和ArrayList<Object>
具有相同的删除,编译器对它们的分配的提示是正确的,如上所述。总之,使用泛型限制这些强制转换与使用相同删除限制构造函数/方法一样重要。
关于java - 相同的删除,但类型不同。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41794484/