java创建集合有的不用泛型_为什么在Java泛型右手边的集合类型没有任何影响?...

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

List myList=new ArrayList();

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

myList.add(101);

我希望我会得到一些编译错误但是这个程序运行正常.但是如果我使用泛型类型List在左侧和右侧的原始类型ArrayList并尝试将int值添加到列表中,我按预期收到编译错误.

List myList=new ArrayList();

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

为什么在Java泛型右手边的集合类型没有任何影响?为什么Java允许我们在没有任何影响时这样做.我正在使用Java 1.6.请解释.

解决方法:

如果您未在左侧提供泛型类型参数,则将List声明为原始类型.这意味着编译器不知道在该列表中存储什么是合法的,并且依赖于程序员来执行适当的检查和转换实例.

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值