gpt4 book ai didi

java - 奇怪的 Java 行为。三元运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:01 25 4
gpt4 key购买 nike

为什么这段代码有效?

Float testFloat = null;
Float f = true ? null : 0f;

为什么会抛出异常?

Float testFloat = null;
Float f = true ? testFloat : 0f;

但最奇怪的是,这段代码也运行成功,没有任何异常:

Float testFloat = null;
Float f = testFloat;

Java 的三元运算符似乎改变了行为。谁能解释一下这是为什么?

最佳答案

行为在 JLS - Conditional Operator 中指定:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

强调我的。所以,在第二种nd情况下:

Float f = true ? testFloat : 0f;

由于第 3 个操作数是基本类型(T),表达式的类型将是 float 类型 - T。因此,拆箱 testFloat 当前是一个null 引用,对float 将导致NPE.


关于第一个st案例,相关部分是最后一个:

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).

所以,根据这个:

null type - S1
float - S2

null type - T1 (boxing null type gives null type)
Float - T2 (float boxed to Float)

然后条件表达式的类型变为 - Float。不需要拆箱 null,因此没有 NPE

关于java - 奇怪的 Java 行为。三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934526/

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