How do I fix "The expression of type List needs unchecked conversion...'?

user46277 picture user46277 · Dec 15, 2008 · Viewed 191k times · Source

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?

Answer

Bruno De Fraine picture Bruno De Fraine · May 17, 2010

This is a common problem when dealing with pre-Java 5 APIs. To automate the solution from erickson, you can create the following generic method:

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for(Object o: c)
      r.add(clazz.cast(o));
    return r;
}

This allows you to do:

List<SyndEntry> entries = castList(SyndEntry.class, sf.getEntries());

Because this solution checks that the elements indeed have the correct element type by means of a cast, it is safe, and does not require SuppressWarnings.