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

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

I called a getElements method which returns Iterable.

I did this:

List elements = (List

        
10条回答
  •  庸人自扰
    2021-02-20 01:25

    Yes, List extends Iterable, but that doesn't mean that you can cast from any Iterable to List - only when the value actually refers to an instance of a type of List. It's entirely possible to implement Iterable without implementing the rest of the List interface... in that case, what would you expect to happen?

    To put it in simpler terms, let's change Iterable to Object and List 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).

提交回复
热议问题