简体   繁体   English

奇怪的行为,Long的Generic ArrayList

[英]Strange behaviour, Generic ArrayList of Long

I have someMethod() which returns Collection<Long> . 我有someMethod()返回Collection<Long>

ArrayList<Long> results = (ArrayList<Long>) someMethod();
Long value = results.get(0);

I get ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long . 我得到ClassCastException: java.util.ArrayList cannot be cast to java.lang.Long Trying System.out.println(results.get(0)); 试试System.out.println(results.get(0)); in fact, it returns eg [32] . 事实上,它返回例如[32] I do not understand this. 我不明白这个。 This is ArrayList of Long! 这是Long的ArrayList! Why get(0) returns ArrayList ? 为什么get(0)返回ArrayList

This helps: 这有助于:

Object o = results.get(0);
ArrayList<Long> al = (ArrayList<Long>) o;
Long val = al.get(0);

but why this is needed? 但为什么需要呢?

Clearly someMethod() is actually returning Collection<List<Long>> , violating declared return type. 显然someMethod()实际上是返回Collection<List<Long>> ,违反了声明的返回类型。 This is possible due to type erasure. 由于类型擦除,这是可能的。 The compiler is happy as long as the class type is correct, generic type can be ignored (the compiler will only raise warning). 只要类类型正确,编译器就很高兴,可以忽略泛型类型(编译器只会引发警告)。 Basically this is a bug in someMethod() . 基本上这是someMethod()一个错误。

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

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