当您混合使用运算符的类型时,条件运算符非常棘手.这是许多Java Puzzlers的主题.
这是一个经典的例子:
System.out.println(true ? Integer.valueOf(1) : Double.valueOf(2));
// prints "1.0"!!!
这是另一个:
System.out.println(true ? '*' : 0); // prints "*"
int zero = 0;
System.out.println(true ? '*' : zero); // prints "42"
而且,正如您刚刚发现的:
System.out.println(true ? 1 : null); // prints "1"
System.out.println(false ? 1 : null); // prints "null"
要了解条件运算符?:的所有复杂性,可能会非常困难.最好的建议是不要在第二和第三操作数中混合使用类型.
以下引用摘录自Java Puzzlers,《 Puzzle 8:Dos Equis》课程:
In summary, it is generally best to use the same type for the second and third operands in conditional expressions. Otherwise, you and the readers of your program must have a thorough understanding of the complex specification for the behavior of these expressions.
JLS参考
本文通过几个具体的示例深入探讨了Java中条件运算符(三元运算符)的使用及可能遇到的问题,特别是不同类型混合使用时的行为表现,并给出了一些建议。
171万+

被折叠的 条评论
为什么被折叠?



