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類的源碼
- 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(){} //構造方法,不需要構造什么
- }
再來看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); //否則就在堆內存中創建
- }
- }
valueOf方法會自動調用IntegerCache這個類,
IntegerCache初始化后內存中就有Integer緩沖池cache[]了,
-128~127區間的int值有其對應的的包裝對象
java使用該機制是為了達到最小化數據輸入和輸出的目的,這是一種優化措施,提高效率
其他的包裝器:
Boolean: (全部緩存)
Byte: (全部緩存)
Character ( <=127 緩存)
Short (-128~127 緩存)
Long (-128~127 緩存)
Float (沒有緩存)
Doulbe (沒有緩存)
====================================================
知道了這個原理我們再來看一些網上關于java的有趣問題,就能知道答案了
下面我們對一網友帖子中的問題的做解答,我當時也是看到這個帖子才baidu學到這些內容的
http://xiaoyu1985ban.iteye.com/blog/1384191
主題:java迷題:等于,還是不等于?
代碼片段1
public static void main(final String[] args) {
Integer a = new Integer(100);
Integer b = 100;
System.out.println(a == b);
}
解答:
結果輸出 false
因為new Integer(100)是指明了再堆內存中創建對象
而Integer b = 100; 這句是自動裝箱,
得到的是Integer緩沖池中的對象,是這句代碼return IntegerCache.cache[100 + 128]
明顯a和b的地址是不一樣的,不是同一個對象
代碼片段2
public static void main(final String[] args) {
Integer a = 100;
Integer b = 100;
System.out.println(a == b);
}
解答:
結果輸出 true
a和b指向了同一個對象,都是IntegerCache.cache[100 + 128]
代碼片段3
public static void main(final String[] args) {
Integer a = 156;
Integer b = 156;
System.out.println(a == b);
}
解答:
結果輸出 false
由于156大于128,它的包裝對象不在緩沖池中,而是執行 return new Integer(156);
new了2次,都在堆內存中,但地址不一樣
代碼片段4
public static void main(final String[] args) {
Integer a = Integer.valueOf(100);
Integer b = 100;
System.out.println(a == b);
}
解答:
結果輸出 true
我們上面說過了,Integer b = 100 就相當于Integer b=Integer.valueOf(100)
所以a和b指向緩沖池中的同一對象