为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

我已经看到它在某处进行了讨论,下面的代码导致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进行比较和计算时所用的方式有关,但此处左右两侧并不以这种方式相互作用。为什么会这样?
查看完整描述

3 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

条件运算符中的数值转换?:

在条件运算符中,如果和都是不同的数字类型,则在编译时将应用以下转换规则,以使它们的类型相等,顺序是:a?b:cbc

  • 这些类型将转换为它们对应的原始类型,这称为unboxing

  • 如果一个操作数是一个常量 int(不在Integer拆箱之前),其值可以用另一种类型表示,则该int操作数将转换为另一种类型。

  • 否则,较小的类型将转换为下一个较大的类型,直到两个操作数具有相同的类型。转换顺序为:
    byte-> short-> int-> long-> float-> double
    char-> int-> long-> float->double

最终,整个条件表达式将获得其第二和第三操作数的类型。

示例:
如果char与组合short,则表达式变为int
如果Integer与组合Integer,则表达式变为Integer
如果final int i = 5与a 组合Character,则表达式变为char
如果short与组合float,则表达式变为float

在问题的例子,200从转换Integerdouble,0.0是装箱从Double进入double和整个条件表达式变为变为double其最终盒装入Double因为obj是类型Object


查看完整回答
反对 回复 2019-09-24
?
慕村9548890

TA贡献1884条经验 获得超4个赞

例:


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.


}


查看完整回答
反对 回复 2019-09-24
  • 3 回答
  • 0 关注
  • 634 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信