I called a getElements
method which returns Iterable
.
I did this:
List elements = (List
You can turn Iterable into a List with
List<Element> elements = Lists.newArrayList( getElements() );
List extends Collection which in turn extends Iterable. You therefore trying to cast to a subtype which won't work unless getElements() really is returning a List (which the signature doesn't in any way guarantee).
See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html
Not all Iterable
s are List
s, thus it's not safe to cast an arbitrary Iterable
to a List
.
Take any Set
for instance, a HashSet
is Iterable
but the elements has no order, so it can't implement the List
interface, and is thus not a List
.
why not:
Iterable<Element> i = ...; //is what you have
List<Element> myList = new LinkedList<Element>();
for (Element e:i) {
myList.add(e);
}
? needs no google lib.
List<Element>
is a type of Iterable<Element>
, but that doesn't mean that all Iterable<Element>
objects are List<Element>
objects. You can cast a List<Element>
as an Iterable<Element>
, but not the other way around.
An apple is a type of fruit, but that doesn't mean that all fruits are apples. You can cast an apple as a fruit, but not the other way around.
From exception message it is clear that
Iterable<Element>
is not castable to List<Element>
SO you need to return List<Element>
from getElements()