我有以下代码部分:

public void deepSearch(File fileToLook,ArrayList<File> fileStorage,DefaultComboBoxModel<String> mod){
        if(fileToLook.isDirectory())
        {
            for(File f:fileToLook.listFiles())
                deepSearch(f,fileStorage,mod);
        }
        else if(fileToLook != null){
            fileStorage.add(fileToLook);
            mod.addElement(fileToLook.getName());
        }
        else
            System.out.println("Reached an end.");
    }


但是eclipse对此给出了无效代码警告:

else
    System.out.println("Reached an end.");


你能解释为什么会这样吗?

最佳答案

好吧,当到达fileToLook语句时,else不能为null,因为如果为null,则第一个条件将引发NullPointerException

重构该方法会更有意义,并避免潜在的NullPointerException

if(fileToLook != null) {
    if(fileToLook.isDirectory()) {
        for(File f:fileToLook.listFiles())
            deepSearch(f,fileStorage,mod);
    } else {
        fileStorage.add(fileToLook);
        mod.addElement(fileToLook.getName());
    }
} else {
    System.out.println("Reached an end."); // not sure if you really need this
                                           // statement. It looks like a debug print to me
}

10-06 05:43