int → Integer),自動調用 valueOf()。xxxValue()(如 intValue())。Java 5 前需手動 new Integer(10),Java 5+ 支援 Integer i = 10;。
Integer i = 10; // 編譯為 Integer.valueOf(10) int n = i; // 編譯為 i.intValue()
Integer.valueOf(int)。Integer.intValue()。Double.valueOf、Character.valueOf 等)。
public static Integer valueOf(int i) {
if (i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
return new Integer(i);
}
IntegerCache 靜態初始化區間內所有整數物件。high 可透過 -XX:AutoBoxCacheMax 調整(預設 127)。
Integer i1 = 100, i2 = 100, i3 = 200, i4 = 200; System.out.println(i1 == i2); // true(快取命中) System.out.println(i3 == i4); // false(新建物件)
Double d1 = 100.0, d2 = 100.0; System.out.println(d1 == d2); // false(Double 無快取)
原因:浮點數在任意區間內個數無限,無法快取。
Boolean b1 = false, b2 = false, b3 = true, b4 = true; System.out.println(b1 == b2); // true System.out.println(b3 == b4); // true
Boolean.valueOf 直接回傳單例 TRUE/FALSE。
.equals(),勿用 ==。