简体   繁体   中英

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) {
            e.printStackTrace();
        }
        i++;
    }
}

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, eg,

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 Commons IO , or simply insert the @SuppressWarnings("unchecked") annotation appropriately, eg,

@SuppressWarnings("unchecked")
Collection<File> myCollection = FileUtils.listFiles(...);

Why do you need a List<File> ? Why not do: Collection<File> files=FileUtils.listFiles(...) ? This won't give you a warning and you can still iterate over your Collection of files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM