- 裝箱就是自動將基本數(shù)據(jù)類型轉(zhuǎn)換為包裝器類型(int-->Integer)讥珍;調(diào)用方法:Integer的valueOf(int) 方法。
- 拆箱就是自動將包裝器類型轉(zhuǎn)換為基本數(shù)據(jù)類型(Integer-->int)偿曙;調(diào)用方法:Integer的intValue方法围小。
自動裝箱和拆箱發(fā)生在編譯器
Integer x = 2; // 裝箱 調(diào)用了 Integer.valueOf(2)
int y = x; // 拆箱 調(diào)用了 X.intValue()
面試題01:以下代碼會輸出什么们豌?
public void Test01(){
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
}
結(jié)果:
true
false
原因:看一下源碼
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache類的實(shí)現(xiàn)為
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
代碼可以看出,在通過valueOf方法創(chuàng)建Integer對象的時候记罚,如果數(shù)值在[-128,127]之間墅诡,便返回指向IntegerCache.cache中已經(jīng)存在的對象的引用;否則創(chuàng)建一個新的Integer對象毫胜。
上面代碼中i1和i2的數(shù)值為100书斜,因此會直接從cache中取已經(jīng)存在的對象,所以i1和i2指向的是同一個對象酵使,而i3和i4則分別指向不同的對象荐吉。
面試題01:以下代碼會輸出什么?
public void test02(){
Double d1 = 100.0;
Double d2 = 100.0;
Double d3 = 100.0;
Double d4 = 100.0;
System.out.println(d1 == d2);
System.out.println(d3 == d4);
}
結(jié)果:
false
false
原因:在某個范圍內(nèi)的整型數(shù)值的個數(shù)是有限的口渔,而浮點(diǎn)數(shù)卻不是样屠。
基本類型對應(yīng)的緩沖池如下:
- boolean values true and false
- all byte values
- short values between128 and 127
- int values between -128 and 127
- char in the range \u0000 to \u007F
面試題03 new Integer(123) 與 Integer.valueOf(123) 的區(qū)別在于:
- new Integer(123) 每次都會新建一個對象;
- Integer.valueOf(123) 會使用緩存池中的對象缺脉,多次調(diào)用會取得同一個對象的引用痪欲。