有問題的線路是return pFile.exists() ? true : null;
。由於它不會引發任何編譯錯誤,因此解釋是什麼。它最終提高了NPE
。需要說明:java中的三元運算符
import java.io.File;
public class Main {
public static void main(String... args) {
boolean accept = accept(new File(""));
System.out.println("accept = " + accept);
}
public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
return pFile.exists() ? true : null; //this line should throw compilation error
}
}
pFile
不null
;你可以看到一個File
被實例化。但顯然該文件不存在。這個問題不是關於pFile
。我對運營商如何處理null
感興趣。
爲什麼不直接返回'pFile.exists()'? –
用以下代碼替換accept(File pFile)方法的主體:'return(pFile == null)? false:pFile.exists();'或者不使用三元運算符,你可以說'return(pFile!= null)&& pFile.exists();'。 – styfle
請參閱我的編輯。是的,我可以寫'return pFile.exists();' – Kowser