简体   繁体   中英

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

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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