第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么三元運算符意外地轉(zhuǎn)換整數(shù)?

為什么三元運算符意外地轉(zhuǎn)換整數(shù)?

我已經(jīng)看到它在某處進行了討論,下面的代碼導致obj成為Double,但它是200.0從左側(cè)打印的。Object obj = true ? new Integer(200) : new Double(0.0);System.out.println(obj);結(jié)果:200.0但是,如果您在右手邊放一個不同的對象,例如BigDecimal,類型obj是Integer理所應當?shù)摹bject obj = true ? new Integer(200) : new BigDecimal(0.0);System.out.println(obj);結(jié)果:200我認為這樣做的原因與將左手邊強制轉(zhuǎn)換double為integer/ double進行比較和計算時所用的方式有關,但此處左右兩側(cè)并不以這種方式相互作用。為什么會這樣?
查看完整描述

3 回答

?
嗶嗶one

TA貢獻1854條經(jīng)驗 獲得超8個贊

條件運算符中的數(shù)值轉(zhuǎn)換?:

在條件運算符中,如果和都是不同的數(shù)字類型,則在編譯時將應用以下轉(zhuǎn)換規(guī)則,以使它們的類型相等,順序是:a?b:cbc

  • 這些類型將轉(zhuǎn)換為它們對應的原始類型,這稱為unboxing。

  • 如果一個操作數(shù)是一個常量 int(不在Integer拆箱之前),其值可以用另一種類型表示,則該int操作數(shù)將轉(zhuǎn)換為另一種類型。

  • 否則,較小的類型將轉(zhuǎn)換為下一個較大的類型,直到兩個操作數(shù)具有相同的類型。轉(zhuǎn)換順序為:
    byte-> short-> int-> long-> float-> double
    char-> int-> long-> float->double

最終,整個條件表達式將獲得其第二和第三操作數(shù)的類型。

示例:
如果char與組合short,則表達式變?yōu)?code>int。
如果Integer與組合Integer,則表達式變?yōu)?code>Integer。
如果final int i = 5與a 組合Character,則表達式變?yōu)?code>char。
如果short與組合float,則表達式變?yōu)?code>float。

在問題的例子,200從轉(zhuǎn)換Integerdouble,0.0是裝箱從Double進入double和整個條件表達式變?yōu)樽優(yōu)?code>double其最終盒裝入Double因為obj是類型Object。


查看完整回答
反對 回復 2019-09-24
?
慕村9548890

TA貢獻1884條經(jīng)驗 獲得超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 關注
  • 707 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號