我如何修复“List类型的表达式需要未经检查的转换......”? [英] How do I fix "The expression of type List needs unchecked conversion...'?

查看:238
本文介绍了我如何修复“List类型的表达式需要未经检查的转换......”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java片段中:

SyndFeedInput fr = new SyndFeedInput();
SyndFeed sf = fr.build(new XmlReader(myInputStream));
List<SyndEntry> entries = sf.getEntries();

最后一行产生警告

类型 List 的表达式需要未经检查的转换以符合列表< SyndEntry>

"The expression of type List needs unchecked conversion to conform to List<SyndEntry>"

解决这个问题的合适方法是什么?

What's an appropriate way to fix this?

推荐答案

由于 getEntries 返回原始列表,它可以保留任何内容。

Since getEntries returns a raw List, it could hold anything.

无警告方法是创建一个新的列表< SyndEntry> ,然后将 sf.getEntries()结果的每个元素转换为 SyndEntry ,然后再将其添加到你的新名单。 Collections.checkedList 为你做这个检查—尽管可以实现它来实现它。

The warning-free approach is to create a new List<SyndEntry>, then cast each element of the sf.getEntries() result to SyndEntry before adding it to your new list. Collections.checkedList does not do this checking for you—although it would have been possible to implement it to do so.

通过自己的演员阵容,您遵守Java泛型的保修条款:如果 ClassCastException ,它将与源代码中的强制转换相关联,而不是编译器插入的不可见强制转换。

By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a ClassCastException is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.

这篇关于我如何修复“List类型的表达式需要未经检查的转换......”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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