"可迭代<组件>无法转换为List< Element>" - 不是`List`是一种`Iterable`? [英] "Iterable<Element> cannot be cast to List<Element>" - Isn't `List` a type of `Iterable`?

查看:129
本文介绍了"可迭代<组件>无法转换为List< Element>" - 不是`List`是一种`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).

这篇关于&QUOT;可迭代&LT;组件&gt;无法转换为List&lt; Element&gt;&quot; - 不是`List`是一种`Iterable`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆