3 回答
TA貢獻1854條經驗 獲得超8個贊
條件運算符中的數值轉換?:
在條件運算符中,如果和都是不同的數字類型,則在編譯時將應用以下轉換規則,以使它們的類型相等,順序是: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。
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.
}
添加回答
舉報
