编程语言
首页 > 编程语言> > 为什么在Java泛型右手边的集合类型没有任何影响?

为什么在Java泛型右手边的集合类型没有任何影响?

作者:互联网

使用Java的Generics功能我创建了一个List对象,在左侧我使用的是原始类型List,在右侧我使用的是泛型类型ArrayList<字符串>.

List myList=new ArrayList<String>();

我在list对象中添加了一个int值.

myList.add(101);

我希望我会得到一些编译错误但是这个程序运行正常.但是如果我使用泛型类型List<字符串>在左侧和右侧的原始类型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声明为原始类型.这意味着编译器不知道在该列表中存储什么是合法的,并且依赖于程序员来执行适当的检查和转换实例.

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

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,collections,generics,java-6
来源: https://codeday.me/bug/20190829/1764170.html