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

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

I called a getElements method which returns Iterable.

I did this:

List elements = (List

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

    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.

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

    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).

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

    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

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

    you can try to place a guard with instanceof:

    if (AnElement instanceof AList){
        //cast
        AList = (AnList)Element
    }
    
    0 讨论(0)
提交回复
热议问题