Moonie Asemani Moonie Asemani - 1 year ago 110
Java Question

How to address Type safety warning Unchecked cast from Collection to List<File> Java 6 without suppress annotation

I have the following code:

public void someMethod(String directory,final String extension) {

List<File> fileList = (List<File>) FileUtils.listFiles(new File(directory), new String[] {extension} , true);
File[] files = new File[fileList.size()];
// ...

for(File f : files) {
// looping...

I get the yellow sqiggley line in my code with the warning:

Type safety: Unchecked cast from Collection to List

How can I fix this?

Edit 1:

Please no suppression annotations, I'd like to understand what is happening. I've tried doing this:

if(fileList instanceof List<?>) {
// data processing here...

this didn't make the warning go away...this is really bothering me...

Edit 2:

I've decided to do this:

List<?> fileList = (List<?>) FileUtils.listFiles(new File(directory), new String[] {extension} , true);

File[] files = new File[fileList.size()];

int i=0;
if(fileList instanceof List<?>) {
for (Object obj : fileList) {
try {
File file = (File)obj;
files[i] = new File(file.getCanonicalPath());
} catch (IOException e) {

Answer Source

Well, first of all, Collection is a superinterface of List, so unless you are sure that your implementation of listFiles() will always return a List, you shouldn't downcast (so as to avoid a ClassCastException). In most cases, if you need a list instead of a collection, it's wiser to simply create a new list from the returned collection, e.g.,

Collection<File> myCollection = FileUtils.listFiles(...);
List<File> myList = new ArrayList<File>(myCollection);

Alternatively, if all you want to do is convert the collection into an array, there's no need to create any list at all. All you have to do is:

Collection<File> myCollection = FileUtils.listFiles(...);
File[] myArray = myCollection.toArray(new File[myCollection.size()]);

If the compiler continues to give you warnings, then your only remaining problem lies with the listFiles() method itself; it's returning the raw type Collection instead of the generic type Collection<File>. To remove the associated warning, either update to the latest version of the FileUtils library, or simply insert the @SuppressWarnings("unchecked") annotation appropriately, e.g.,

Collection<File> myCollection = FileUtils.listFiles(...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download