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

后端 未结 10 1618
生来不讨喜
生来不讨喜 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.

提交回复
热议问题