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?
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:
This allows you to do:
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
.Since
getEntries
returns a rawList
, it could hold anything.The warning-free approach is to create a new
List<SyndEntry>
, then cast each element of thesf.getEntries()
result toSyndEntry
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.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.