“Iterable cannot be cast to List” - Isn't `List` a type of `Iterable`?

后端 未结 10 1608
生来不讨喜
生来不讨喜 2021-02-20 00:27

I called a getElements method which returns Iterable.

I did this:

List elements = (List

        
相关标签:
10条回答
  • 2021-02-20 01:02

    You can turn Iterable into a List with

    List<Element> elements = Lists.newArrayList( getElements() );
    
    0 讨论(0)
  • 2021-02-20 01:06

    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

    0 讨论(0)
  • 2021-02-20 01:10

    Not all Iterables are Lists, 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.

    0 讨论(0)
  • 2021-02-20 01:15

    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.

    0 讨论(0)
  • 2021-02-20 01:18

    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.

    0 讨论(0)
  • 2021-02-20 01:18

    From exception message it is clear that Iterable<Element> is not castable to List<Element>

    SO you need to return List<Element> from getElements()

    0 讨论(0)
提交回复
热议问题