简体   繁体   中英

Strange behaviour, Generic ArrayList of Long

I have someMethod() which returns 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 . Trying System.out.println(results.get(0)); in fact, it returns eg [32] . I do not understand this. This is ArrayList of Long! Why get(0) returns 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. 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() .

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