0

怎么会是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)
4

1 回答 1

1

如果我们首先了解类型擦除对于 Java 中的泛型意味着什么,就会更容易理解为什么会发生这种情况。在继续之前,请查看 Oracle 文档中的类型擦除。

既然您知道类型擦除的含义,让我们看看 Oracle 文档对泛型的说法。

从文档中可以清楚地看出,泛型的主要目标是提供更严格的编译时检查。如果编译器不强制检查泛型转换,那将是相当矛盾的。为了讨论起见,假设允许以下语句:

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>具有相同的擦除,但编译器在抱怨它们的分配是正确的,如上所述。总之,使用泛型限制这些强制转换与使用相同擦除限制构造函数/方法同样重要。

于 2017-01-22T19:09:06.297 回答