简体   繁体   English

在Java集合中使用泛型的意外行为

[英]Unexpected behavior using generics with Java Collections

Something weird i've just realized: 我刚刚意识到的事情很奇怪:

Java documentation states that List collection has a method T get(int index) ... as you see the method returns T Java文档指出List集合具有方法T get(int index)...如您所见,该方法返回T

However i can do: 但是我可以做到:

List<Integer> l1 = new ArrayList<>();
l1.add(1);
List l2 = l1;
l2.add("Hello my friend");
Object o2 = l1.get(1);
System.out.println(o2);

And the result is "Hello my friend" !! 结果是“你好我的朋友”! ... this does not comply with stated in documentation since the result shall be Integer! ...这不符合文档中所述,因为结果应为Integer!

Is there any other possible explanaition? 还有其他可能的解释吗?

Generics are compile-time checks. 泛型是编译时检查。 All bets are off once you start using raw types...which you are. 一旦开始使用原始类型,所有赌注都将关闭。 This is why raw types are dangerous, and should never be used in new code. 这就是为什么原始类型很危险,并且绝对不能在新代码中使用的原因。

List l2不是通用的,因此它基本上是List<Object> ,当您使用非通用列表时,添加到列表中的所有内容都将成为Object ,由您来正确使用它们,否则您将得到ClassCastException

如果您将l2声明为泛型,那么您将得到一个编译时错误(如果您的编译器配置为抱怨这些事情)。

final List<Integer> l2 = l1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM