包裝器
有些時候,我們需要把類似于int,double這樣的基本數(shù)據(jù)類型轉(zhuǎn)成對象威蕉,于是設(shè)計者就給每一個基本數(shù)據(jù)類型都配置了一個對應(yīng)的類吧寺,這些類被稱為包裝器窜管。
包裝器整體來說分為四大種:
- Number,Number類派生出了Integer稚机,Double幕帆,Long,F(xiàn)loat赖条,Short失乾,Byte這六個小類分別代表了int,double纬乍,long碱茁,float,short仿贬,byte這六種基本數(shù)據(jù)類型纽竣。
- Character,對應(yīng)的基本數(shù)據(jù)類型是char诅蝶。
- Void退个,對應(yīng)的是關(guān)鍵字void募壕,這個類我們會經(jīng)常在反射中看到调炬,用于表示方法的返回值是void,這里不再贅述舱馅,后面反射章節(jié)詳細(xì)講解缰泡。
- Boolean,對應(yīng)的是基本數(shù)據(jù)類型boolean代嗤。
要記住下面兩點包裝器的特性:
- 包裝器是不可變的棘钞,一旦構(gòu)造了包裝器,就不允許更改包裝在其中的值干毅。
- 包裝器是final定義的宜猜,不允許定義它的子類。
自動裝箱和自動拆箱
ArrayList<Integer> list = new ArrayList<>();
list.add(3);
int x = list.get(0);
自動裝箱
當(dāng)我們添加int值 到一個集合元素全部是Integer的集合中去時候硝逢,這個過程發(fā)生了什么姨拥?
list.add(3);
//實際上面的代碼會被編譯器給自動的變成下面的這個代碼
list.add(Integer.valueOf(3))
編譯器在其中所作的這個事情就叫做自動裝箱。
自動拆箱
當(dāng)我們?nèi)〕鲆粋€集合中的元素并將這個元素賦給一個int類型的值的時候渠鸽,這其中又發(fā)生了什么呢叫乌?
int x = list.get(0);
//實際上面的代碼會被編譯器給自動的變成下面的這個代碼
int x = list.get(0).intValue();
編譯器這其中所作的這個事情就叫做自動拆箱
自動裝箱和自動拆箱中的坑
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 300;
Integer i4 = 300;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
這是一道經(jīng)典的面試題,打印出來的結(jié)果是:
true
false
為什么會發(fā)生這樣的事情徽缚,我們記得自動裝箱的時候會自動調(diào)用Integer的valueOf方法憨奸,我們現(xiàn)在來看一下這個方法的源碼:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
而這個IntegerCache是什么呢?
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() {}
}
從這2段代碼可以看出凿试,在通過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則是分別指向不同的對象麻诀。
這樣我們就不難理解為什么一個是false,一個是true了傲醉。
原創(chuàng)文章蝇闭,文筆有限,才疏學(xué)淺硬毕,文中若有不正之處呻引,萬望告知