How do I fix "The expression of type List needs un

2019-01-03 21:17发布

In the Java snippet:

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

the last line generates the warning

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

What's an appropriate way to fix this?

9条回答
爷、活的狠高调
2楼-- · 2019-01-03 21:49

It looks like SyndFeed is not using generics.

You could either have an unsafe cast and a warning suppression:

@SuppressWarnings("unchecked")
List<SyndEntry> entries = (List<SyndEntry>) sf.getEntries();

or call Collections.checkedList - although you'll still need to suppress the warning:

@SuppressWarnings("unchecked")
List<SyndEntry> entries = Collections.checkedList(sf.getEntries(), SyndEntry.class);
查看更多
聊天终结者
3楼-- · 2019-01-03 21:49

Did you write the SyndFeed?

Does sf.getEntries return List or List<SyndEntry>? My guess is it returns List and changing it to return List<SyndEntry> will fix the problem.

If SyndFeed is part of a library, I don't think you can remove the warning without adding the @SuppressWarning("unchecked") annotation to your method.

查看更多
混吃等死
4楼-- · 2019-01-03 21:49

If you look at the javadoc for the class SyndFeed (I guess you are referring to the class com.sun.syndication.feed.synd.SyndFeed), the method getEntries() doesn't return java.util.List<SyndEntry>, but returns just java.util.List.

So you need an explicit cast for this.

查看更多
叛逆
5楼-- · 2019-01-03 21:49

Even easier

return new ArrayList<?>(getResultOfHibernateCallback(...))

查看更多
不美不萌又怎样
6楼-- · 2019-01-03 21:55

If you don't want to put @SuppressWarning("unchecked") on each sf.getEntries() call, you can always make a wrapper that will return List.

See this other question

查看更多
该账号已被封号
7楼-- · 2019-01-03 21:58

If you are using Guava and all you want to do is iterate through your values:

for(SyndEntry entry: Iterables.filter(sf.getEntries(), SyndEntry.class){
  ...
}

If you need an actual List you can use

List<SyndEntry> list = Lists.newArrayList(
    Iterables.filter(sf.getEntries(), SyndEntry.class));

or

List<SyndEntry> list = ImmutableList.copyOf(
    Iterables.filter(sf.getEntries(), SyndEntry.class));
查看更多
登录 后发表回答