詳解Java 自動裝箱與自動拆箱
包裝器
有些時候,我們需要把類似于int,double這樣的基本數據類型轉成對象,于是設計者就給每一個基本數據類型都配置了一個對應的類,這些類被稱為包裝器。
包裝器整體來說分為四大種:
Number,Number類派生出了Integer,Double,Long,Float,Short,Byte這六個小類分別代表了int,double,long,float,short,byte這六種基本數據類型。 Character,對應的基本數據類型是char。 Void,對應的是關鍵字void,這個類我們會經常在反射中看到,用于表示方法的返回值是void,這里不再贅述,后面反射章節詳細講解。 Boolean,對應的是基本數據類型boolean。要記住下面兩點包裝器的特性:
包裝器是不可變的,一旦構造了包裝器,就不允許更改包裝在其中的值。
包裝器是final定義的,不允許定義它的子類。自動裝箱和自動拆箱
ArrayList<Integer> list = new ArrayList<>();list.add(3);int x = list.get(0);
自動裝箱
當我們添加int值 到一個集合元素全部是Integer的集合中去時候,這個過程發生了什么?
list.add(3);//實際上面的代碼會被編譯器給自動的變成下面的這個代碼list.add(Integer.valueOf(3))
編譯器在其中所作的這個事情就叫做自動裝箱。
自動拆箱
當我們取出一個集合中的元素并將這個元素賦給一個int類型的值的時候,這其中又發生了什么呢?
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);
這是一道經典的面試題,打印出來的結果是:
truefalse
為什么會發生這樣的事情,我們記得自動裝箱的時候會自動調用Integer的valueOf方法,我們現在來看一下這個方法的源碼:
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方法創建Integer對象的時候,如果數值在[-128,127]之間,便返回指向IntegerCache.cache中已經存在的對象的引用;否則創建一個新的Integer對象。
上面的代碼中i1和i2的數值為100,因此會直接從cache中取已經存在的對象,所以i1和i2指向的是同一個對象,而i3和i4則是分別指向不同的對象。
這樣我們就不難理解為什么一個是false,一個是true了。
其他的包裝器的valueOf方法也有不同的實現和不同的范圍,具體的我們會在源碼深度解析專欄來分析,敬請期待~
以上就是詳解Java 自動裝箱與自動拆箱的詳細內容,更多關于Java 自動裝箱與自動拆箱的資料請關注好吧啦網其它相關文章!
相關文章: