gpt4 book ai didi

java - 需要解释 : ternary operator in java

转载 作者:行者123 更新时间:2023-12-03 22:26:45 24 4
gpt4 key购买 nike

有问题的行是 return pFile.exists() ?真:空;。由于它不会引发任何编译错误,对此有何解释。它最终引发了 NPE

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。我对运算符(operator)如何处理 null 很感兴趣。

最佳答案

你的代码相当于:

public static boolean accept(File pFile) {
System.out.println(pFile.exists()); // prints: false, so pFile is not null
Boolean tmp = pFile.exists() ? true : null;
return (boolean) tmp;
}

换句话说,在这种情况下,条件运算符的类型是Boolean,然后将值拆箱以返回boolean。当 null 被拆箱时,你会得到一个异常。

来自 section 15.25 Java 语言规范:

Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

我相信这就是适用于此的情况,尽管我承认它并不像它可能的那样清楚。

关于java - 需要解释 : ternary operator in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7466669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com