詳解Java 自動裝箱與自動拆箱
包裝器
有些時候,我們需要把類似于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é)詳細講解。 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é)果是:
truefalse
為什么會發(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了。
其他的包裝器的valueOf方法也有不同的實現(xiàn)和不同的范圍,具體的我們會在源碼深度解析專欄來分析,敬請期待~
以上就是詳解Java 自動裝箱與自動拆箱的詳細內(nèi)容,更多關(guān)于Java 自動裝箱與自動拆箱的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)2. 教你如何寫出可維護的JS代碼3. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……4. idea設(shè)置自動導(dǎo)入依賴的方法步驟5. python pymysql鏈接數(shù)據(jù)庫查詢結(jié)果轉(zhuǎn)為Dataframe實例6. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)7. docker /var/lib/docker/aufs/mnt 目錄清理方法8. 淺談SpringMVC jsp前臺獲取參數(shù)的方式 EL表達式9. IDEA版最新MyBatis程序配置教程詳解10. 詳解Java內(nèi)部類——匿名內(nèi)部類
