"可迭代<组件>无法转换为List< Element>" - 不是`List`是一种`Iterable`? [英] "Iterable<Element> cannot be cast to List<Element>" - Isn't `List` a type of `Iterable`?
问题描述
我调用了 getElements
方法,该方法返回 Iterable< Element>
。
I called a getElements
method which returns Iterable<Element>
.
我这样做了:
List<Element> elements = (List<Element>) getElements();
这会产生错误:
java.lang.ClassCastException: com.utesy.Element$3
cannot be cast to java.util.List
我认为列表
是一种 Iterable
?
I thought a List
was a type of Iterable
?
推荐答案
是,列表< T>
扩展 Iterable< T>
,但这并不意味着你可以从任何 Iterable< T>
到列表< T>
- 仅当值实际引用类型为 List<的实例时; T>
。完全可以实现 Iterable< T>
而无需实现其余的 List< T>
界面...那种情况,你期望会发生什么?
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?
简单来说,让我们改变 Iterable< T>
到对象
和列表< T>
到字符串
。 字符串
extends Object
,因此您可以尝试从进行投射对象
到字符串
...但是如果引用实际上引用了<,则转换只会在执行时成功code> String (或为空)。
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).
这篇关于"可迭代<组件>无法转换为List< Element>" - 不是`List`是一种`Iterable`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!