一、什么是裝箱,什么是拆箱
裝箱:把基本數(shù)據(jù)類(lèi)型轉(zhuǎn)換為包裝類(lèi)。
拆箱:把包裝類(lèi)轉(zhuǎn)換為基本數(shù)據(jù)類(lèi)型。
基本數(shù)據(jù)類(lèi)型所對(duì)應(yīng)的包裝類(lèi):
int(幾個(gè)字節(jié)4)- Integer
byte(1)- Byte
short(2)- Short
long(8)- Long
float(4)- Float
double(8)- Double
char(2)- Character
boolean(未定義)- Boolean
免費(fèi)在線視頻學(xué)習(xí)教程推薦:java視頻教程
二、先來(lái)看看手動(dòng)裝箱和手動(dòng)拆箱
例子:拿int和Integer舉例
Integer i1=Integer.valueOf(3); int i2=i1.intValue();
手動(dòng)裝箱是通過(guò)valueOf完成的,大家都知道 = 右邊值賦給左邊,3是一個(gè)int類(lèi)型的,賦給左邊就變成了Integer包裝類(lèi)。
手動(dòng)拆箱是通過(guò)intValue()完成的,通過(guò)代碼可以看到 i1 從Integer變成了int
三、手動(dòng)看完了,來(lái)看自動(dòng)的
為了減輕技術(shù)人員的工作,java從jdk1.5之后變?yōu)榱俗詣?dòng)裝箱與拆箱,還拿上面那個(gè)舉例:
手動(dòng):
Integer i1=Integer.valueOf(3); int i2=i1.intValue();
自動(dòng)
Integer i1=3; int i2=i1;
這是已經(jīng)默認(rèn)自動(dòng)裝好和拆好了。
四、從幾道題目中加深對(duì)自動(dòng)裝箱和拆箱的理解
(1)
Integer a = 100; int b = 100; System.out.println(a==b);結(jié)果為 true
原因:a 會(huì)自動(dòng)拆箱和 b 進(jìn)行比較,所以為 true
(2)
Integer a = 100; Integer b = 100; System.out.println(a==b);//結(jié)果為true Integer a = 200; Integer b = 200; System.out.println(a==b);//結(jié)果為false
這就發(fā)生一個(gè)有意思的事了,為什么兩個(gè)變量一樣的,只有值不一樣的一個(gè)是true,一個(gè)是false。
原因:這種情況就要說(shuō)一下 == 這個(gè)比較符號(hào)了,== 比較的內(nèi)存地址,也就是new 出來(lái)的對(duì)象的內(nèi)存地址,看到這你們可能會(huì)問(wèn)這好像沒(méi)有new啊,但其實(shí)Integer a=200; 200前面是默認(rèn)有 new Integer的,所用內(nèi)存地址不一樣 == 比較的就是 false了,但100為什么是true呢?這是因?yàn)?java中的常量池 我們可以點(diǎn)開(kāi) Integer的源碼看看。
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; }
在對(duì) -128到127 之間的進(jìn)行比較時(shí),不會(huì)new 對(duì)象,而是直接到常量池中獲取,所以100是true,200超過(guò)了這個(gè)范圍然后進(jìn)行了 new 的操作,所以內(nèi)存地址是不同的。
(3)
Integer a = new Integer(100); Integer b = 100; System.out.println(a==b); //結(jié)果為false
這跟上面那個(gè)100的差不多啊,從常量池中拿,為什么是false呢?
原因:new Integer(100)的原因,100雖然可以在常量池中拿,但架不住你直接給new 了一個(gè)對(duì)象啊,所用這倆內(nèi)存地址是不同的。
(4)
Integer a = 100; Integer b= 100; System.out.println(a == b); //結(jié)果true a = 200; b = 200; System.out.println(c == d); //結(jié)果為false
原因:= 號(hào) 右邊值賦給左邊a,b已經(jīng)是包裝類(lèi)了,200不在常量池中,把int 類(lèi)型200 賦給包裝類(lèi),自動(dòng)裝箱又因?yàn)椴辉诔A砍刂兴阅J(rèn) new了對(duì)象,所以結(jié)果為false。