您的三元基礎和條件,基於代碼的等價的說法是錯誤的。
此代碼:
integer ? (int) bar : bar;
必須返回單一類型,那就是double
,由於bar
是雙,和(int) bar
可以被提升到兩倍。
這樣在
Object foo = integer ? (int) bar : bar;
的RHS被autoboxed到Double
。
void ternary(double bar, boolean integer) {
Object foo = integer ? (int) bar : bar;
}
反編譯:
void ternary(double, boolean);
Code:
0: iload_3
1: ifeq 10
4: dload_1
5: d2i
// int promoted to double here.
6: i2d
7: goto 11
10: dload_1
// double autoboxed to Double here.
11: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
14: astore 4
16: return
在條件形式,沒有從int到雙推廣:在肯定的情況下分配給foo
表達式爲int
類型(autoboxed爲整數),並在負案是double
型(autoboxed爲Double)的:
void conditional(double bar, boolean integer) {
Object foo;
if (integer) {
foo = (int) bar;
}
else {
foo = bar;
}
}
void conditional(double, boolean);
Code:
0: iload_3
1: ifeq 14
4: dload_1
5: d2i
6: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
9: astore 4
11: goto 20
14: dload_1
15: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
18: astore 4
20: return
因爲'integer'是'FALSE' –
我建議包括所有releva nt代碼(包括「整數」的初始化)。 – obscurite
Foo是一個對象,通過(Integer)而不是(int)投射是否明智? – vdolez