jdk1.5以后
用Integer舉例
Integer a = 3; 這是自動裝箱
int i = new Integer(2); 這是自動拆箱
就是基本類型和其對應的包裝類型在需要的時候可以互相轉換,具體過程由編譯器完成
比如自動裝箱:
Integer a=3;
其實編譯器調用的是static Integer valueOf(int i)這個方法
查閱JDK知道,
valueOf(int i)返回一個表示指定的 int 值的 Integer 對象
那么就變成這樣: Integer a=3; => Integer a=Integer.valueOf(3);
對應的 int intValue() 返回該 Integer對象的int值,是拆箱
我們再來看Integer緩存,
下面是IntegerCache類的源碼
用Integer舉例
Integer a = 3; 這是自動裝箱
int i = new Integer(2); 這是自動拆箱
就是基本類型和其對應的包裝類型在需要的時候可以互相轉換,具體過程由編譯器完成
比如自動裝箱:
Integer a=3;
其實編譯器調用的是static Integer valueOf(int i)這個方法
查閱JDK知道,
valueOf(int i)返回一個表示指定的 int 值的 Integer 對象
那么就變成這樣: Integer a=3; => Integer a=Integer.valueOf(3);
對應的 int intValue() 返回該 Integer對象的int值,是拆箱
我們再來看Integer緩存,
下面是IntegerCache類的源碼
private static class IntegerCache //定義類名
{
static final int high;
static final Integer cache[]; //cache緩存是一個存放Integer類型的數組
static //初始化
{
final int low = -128; //最小值是固定的
int h = 127; //最大值暫時是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; //此時high就是127
cache = new Integer[(high - low) + 1]; //有256個元素
int j = low; //j的初始值是-128
for(int k = 0; k < cache.length; k++) //緩存區間數據
cache[k] = new Integer(j++); //將-128~127包裝成256個對象存入緩存
}
private IntegerCache(){} //構造方法,不需要構造什么
}
{
static final int high;
static final Integer cache[]; //cache緩存是一個存放Integer類型的數組
static //初始化
{
final int low = -128; //最小值是固定的
int h = 127; //最大值暫時是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; //此時high就是127
cache = new Integer[(high - low) + 1]; //有256個元素
int j = low; //j的初始值是-128
for(int k = 0; k < cache.length; k++) //緩存區間數據
cache[k] = new Integer(j++); //將-128~127包裝成256個對象存入緩存
}
private IntegerCache(){} //構造方法,不需要構造什么
}
再來看valueOf方法
public static Integer valueOf(int i)
{
if(i >= -128 && i <= IntegerCache.high)
{
//如果i在-128~127之間,就直接在緩存中取出i的Integer類型對象
return IntegerCache.cache[i + 128];
}
else
{
return new Integer(i); //否則就在堆內存中創建
}
}
{
if(i >= -128 && i <= IntegerCache.high)
{
//如果i在-128~127之間,就直接在緩存中取出i的Integer類型對象
return IntegerCache.cache[i + 128];
}
else
{
return new Integer(i); //否則就在堆內存中創建
}
}
valueOf方法會自動調用IntegerCache這個類,
IntegerCache初始化后內存中就有Integer緩沖池cache[]了,
-128~127區間的int值有其對應的的包裝對象
java使用該機制是為了達到最小化數據輸入和輸出的目的,這是一種優化措施,提高效率
其他的包裝器:
Boolean: (全部緩存)
Byte: (全部緩存)
Character ( <=127 緩存)
Short (-128~127 緩存)
Long (-128~127 緩存)
Float (沒有緩存)
Doulbe (沒有緩存)
IntegerCache初始化后內存中就有Integer緩沖池cache[]了,
-128~127區間的int值有其對應的的包裝對象
java使用該機制是為了達到最小化數據輸入和輸出的目的,這是一種優化措施,提高效率
其他的包裝器:
Boolean: (全部緩存)
Byte: (全部緩存)
Character ( <=127 緩存)
Short (-128~127 緩存)
Long (-128~127 緩存)
Float (沒有緩存)
Doulbe (沒有緩存)