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 e.g. [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 returningCollection<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 insomeMethod().