为什么三元运算符意外地转换整数?

我已经看到它在某处进行了讨论,下面的代码导致obj成为Double,但它是200.0从左侧打印的。


Object obj = true ? new Integer(200) : new Double(0.0);


System.out.println(obj);

结果:200.0


但是,如果您在右手边放一个不同的对象,例如BigDecimal,类型obj是Integer理所应当的。


Object obj = true ? new Integer(200) : new BigDecimal(0.0);


System.out.println(obj);

结果:200


我认为这样做的原因与将左手边强制转换double为integer/ double进行比较和计算时所用的方式有关,但此处左右两侧并不以这种方式相互作用。


为什么会这样?


慕神8447489
浏览 640回答 3
3回答

哔哔one

条件运算符中的数值转换?:在条件运算符中,如果和都是不同的数字类型,则在编译时将应用以下转换规则,以使它们的类型相等,顺序是:a?b:cbc这些类型将转换为它们对应的原始类型,这称为unboxing。如果一个操作数是一个常量 int(不在Integer拆箱之前),其值可以用另一种类型表示,则该int操作数将转换为另一种类型。否则,较小的类型将转换为下一个较大的类型,直到两个操作数具有相同的类型。转换顺序为:byte-> short-> int-> long-> float-> doublechar-> int-> long-> float->double最终,整个条件表达式将获得其第二和第三操作数的类型。示例:如果char与组合short,则表达式变为int。如果Integer与组合Integer,则表达式变为Integer。如果final int i = 5与a 组合Character,则表达式变为char。如果short与组合float,则表达式变为float。在问题的例子,200从转换Integer成double,0.0是装箱从Double进入double和整个条件表达式变为变为double其最终盒装入Double因为obj是类型Object。

慕村9548890

例:public static void main(String[] args) {    int i = 10;    int i2 = 10;    long l = 100;    byte b = 10;    char c = 'A';    Long result;    // combine int with int result is int compiler error   // result = true ? i : i2; // combine int with int, the expression becomes int    //result = true ? b : c; // combine byte with char, the expression becomes int    //combine int with long result will be long    result = true ? l : i; // success - > combine long with int, the expression becomes long    result = true ? i : l; // success - > combine int with long, the expression becomes long    result = true ? b : l; // success - >  combine byte with long, the expression becomes long    result = true ? c : l; // success - >  char long with long, the expression becomes long    Integer intResult;    intResult = true ? b : c; // combine char with byte, the expression becomes int.   // intResult = true ? l : c; // fail combine long with char, the expression becomes long.}
打开App,查看更多内容
随时随地看视频慕课网APP