I called a getElements
method which returns Iterable
.
I did this:
List elements = (List
List implements the Iterable interface but this doesn't mean Iterable can be cast back to List. Iterable is much more general and may be Hash or some exotic type that bears no relation to List. (It looks like getElements() returns an instance of some anonymous inner class contained alongside getElements within its class).
If getElements would happen to contain Lists then this would be a valid cast. As the type returned by getElements() wasn't actually a List this produces a run-time error.
Yes, List<T>
extends Iterable<T>
, but that doesn't mean that you can cast from any Iterable<T>
to List<T>
- only when the value actually refers to an instance of a type of List<T>
. It's entirely possible to implement Iterable<T>
without implementing the rest of the List<T>
interface... in that case, what would you expect to happen?
To put it in simpler terms, let's change Iterable<T>
to Object
and List<T>
to String
. String
extends Object
, so you can try to cast from Object
to String
... but the cast will only succeed at execution time if the reference actually refers to a String
(or is null).
List
is a subinterface of Iterable
meaning that List includes pretty much everything that Iterable has, however not the other way around. So not all methods in a List instance would have an equivalent in Iterable.
Try to avoid that sort of casting.
I would recommend you to take a quick look at the Java 6 API and the tutorials covering casting
you can try to place a guard with instanceof
:
if (AnElement instanceof AList){
//cast
AList = (AnList)Element
}