jdk1.5以后
用Integer舉例
Integer a = 3; 這是自動(dòng)裝箱
int i = new Integer(2); 這是自動(dòng)拆箱
就是基本類型和其對(duì)應(yīng)的包裝類型在需要的時(shí)候可以互相轉(zhuǎn)換,具體過程由編譯器完成
比如自動(dòng)裝箱:
Integer a=3;
其實(shí)編譯器調(diào)用的是static Integer valueOf(int i)這個(gè)方法
查閱JDK知道,
valueOf(int i)返回一個(gè)表示指定的 int 值的 Integer 對(duì)象
那么就變成這樣: Integer a=3; => Integer a=Integer.valueOf(3);
對(duì)應(yīng)的 int intValue() 返回該 Integer對(duì)象的int值,是拆箱
我們?cè)賮砜碔nteger緩存,
下面是IntegerCache類的源碼
private static class IntegerCache //定義類名
{
static final int high;
static final Integer cache[]; //cache緩存是一個(gè)存放Integer類型的數(shù)組
static //初始化
{
final int low = -128; //最小值是固定的
int h = 127; //最大值暫時(shí)是127
if (integerCacheHighPropValue != null) //這段if代碼不用深究,是一些判斷,我看得眼花啊
{
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h; //此時(shí)high就是127
cache = new Integer[(high - low) + 1]; //有256個(gè)元素
int j = low; //j的初始值是-128
for(int k = 0; k < cache.length; k++) //緩存區(qū)間數(shù)據(jù)
cache[k] = new Integer(j++); //將-128~127包裝成256個(gè)對(duì)象存入緩存
}
private IntegerCache(){} //構(gòu)造方法,不需要構(gòu)造什么
}
再來看valueOf方法
public static Integer valueOf(int i)
{
if(i >= -128 && i <= IntegerCache.high)
{
//如果i在-128~127之間,就直接在緩存中取出i的Integer類型對(duì)象
return IntegerCache.cache[i + 128];
}
else
{
return new Integer(i); //否則就在堆內(nèi)存中創(chuàng)建
}
}
valueOf方法會(huì)自動(dòng)調(diào)用IntegerCache這個(gè)類,
IntegerCache初始化后內(nèi)存中就有Integer緩沖池cache[]了,
-128~127區(qū)間的int值有其對(duì)應(yīng)的的包裝對(duì)象
java使用該機(jī)制是為了達(dá)到最小化數(shù)據(jù)輸入和輸出的目的,這是一種優(yōu)化措施,提高效率
其他的包裝器:
Boolean: (全部緩存)
Byte: (全部緩存)
Character ( <=127 緩存)
Short (-128~127 緩存)
Long (-128~127 緩存)
Float (沒有緩存)
Doulbe (沒有緩存)
posted on 2012-02-01 10:25
墻頭草 閱讀(276)
評(píng)論(0) 編輯 收藏