在下面的类中,两个方法的返回类型与三元运算符的想法不一致:
return condition?a:b;
等同于
if(condition) {
return a;
} else{
return b;
}
第一个返回一个双精度型,第二个返回一个长整型:
public class IfTest {
public static Long longValue = 1l;
public static Double doubleValue = null;
public static void main(String[] args) {
System.out.println(getWithIf().getClass());// outpus Long
System.out.println(getWithQuestionMark().getClass());// outputs Double
}
public static Object getWithQuestionMark() {
return doubleValue == null ? longValue : doubleValue;
}
public static Object getWithIf() {
if (doubleValue == null) {
return longValue;
} else {
return doubleValue;
}
}
}
我可以想象这与编译器狭义地转换getWithQuestionMark()
的返回类型有关,但是这种语言明智吗?这肯定不是我所期望的。
欢迎有任何见解!
编辑:下面有非常好的答案。此外,@sakthisundar引用的以下问题探索了在三元运算符中发生的类型提升的另一个副作用:Tricky ternary operator in Java - autoboxing
https://stackoverflow.com/questions/12108998
复制相似问题