gpt4 book ai didi

java - 为什么在 Java 泛型右侧的集合类型中没有任何作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:33 25 4
gpt4 key购买 nike

我使用 Java 的泛型特性创建了一个 List 对象,在左侧我使用原始类型 List,而在右侧我使用泛型类型 ArrayList< String >。

List myList=new ArrayList<String>();

然后我在列表对象中添加了一个 int 值。

myList.add(101);

我希望我会得到一些编译错误,但这个程序运行良好。但是如果我在左侧使用泛型 List< String > 并在右侧使用原始类型 ArrayList 并尝试添加一个 int值添加到列表中,我收到了预期的编译错误。

List<String> myList=new ArrayList();
myList.add(101);//The method add(int, String) in the type List<String> is not applicable for the arguments (int)

为什么在 Java 泛型右侧的集合类型没有任何作用?以及为什么 Java 在它没有任何效果的情况下允许我们这样做。我使用的是 Java 1.6。请解释。

最佳答案

如果您没有在左侧提供通用类型参数,List 将被声明为原始 类型。这意味着编译器不知道在该列表中存储什么是合法的或不合法的,并且依赖于程序员执行适当的 instanceof 检查和转换。

原始类型还具有消除它们出现的类中的所有泛型类型信息的效果。

JLS 提供了一个 much more detailed look at raw types.您应该会在 IDE 中或编译器中看到有关原始类型赋值的警告:

To make sure that potential violations of the typing rules are always flagged, some accesses to members of a raw type will result in compile-time unchecked warnings. The rules for compile-time unchecked warnings when accessing members or constructors of raw types are as follows:

At an assignment to a field: if the type of the left-hand operand is a raw type, then a compile-time unchecked warning occurs if erasure changes the field's type.

At an invocation of a method or constructor: if the type of the class or interface to search (§15.12.1) is a raw type, then a compile-time unchecked warning occurs if erasure changes any of the formal parameter types of the method or constructor.

No compile-time unchecked warning occurs for a method call when the formal parameter types do not change under erasure (even if the result type and/or throws clause changes), for reading from a field, or for a class instance creation of a raw type.

关于java - 为什么在 Java 泛型右侧的集合类型中没有任何作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29977394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com