3 回答

TA貢獻1854條經(jīng)驗 獲得超8個贊
條件運算符中的數(shù)值轉(zhuǎn)換?:
在條件運算符中,如果和都是不同的數(shù)字類型,則在編譯時將應用以下轉(zhuǎn)換規(guī)則,以使它們的類型相等,順序是:a
?
b
:
c
b
c
這些類型將轉(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)換Integer
成double
,0.0是裝箱從Double
進入double
和整個條件表達式變?yōu)樽優(yōu)?code>double其最終盒裝入Double
因為obj
是類型Object
。

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.
}
添加回答
舉報