Integer和Int類(lèi)型的比較
Integer 類(lèi)型是一個(gè)對(duì)象類(lèi),它是將一個(gè)int的基本類(lèi)型進(jìn)行裝箱包裝,當(dāng)我們調(diào)用integer的對(duì)象的時(shí)候,Integer會(huì)指向它所包裝的int基本類(lèi)型的地址。
如果將Integer和int類(lèi)型進(jìn)行比較時(shí),系統(tǒng)會(huì)將Integer自動(dòng)轉(zhuǎn)換成int類(lèi)型,這時(shí)候我們?cè)诒容^int類(lèi)型的時(shí)候會(huì)自動(dòng)的對(duì)這塊地址的值進(jìn)行比較而非對(duì)內(nèi)存比較.觀察下面的例子:
(推薦教程:java快速入門(mén))
public static Integer getIntegerExample1 = 128 ; public static int getIntExample1 = 128 ; System.out.print("結(jié)果: "); System.out.println(getIntegerExample1 == getIntExample1);
結(jié)果: true
當(dāng)我們對(duì)兩個(gè)Integer類(lèi)型進(jìn)行比較時(shí),那么系統(tǒng)會(huì)對(duì)它的內(nèi)存地址進(jìn)行比較.因?yàn)閮?nèi)存分配的地址不同,所以結(jié)果是不同.觀察下面的例子:
public static Integer getIntegerExample3 = 128 ; public static Integer getIntegerExample_3 = 128 ; System.out.print("結(jié)果: "); System.out.println(getIntegerExample3 == getIntegerExample_3);
結(jié)果: false
然而我們還有一種情況,就是當(dāng)Integer值的大小在-127-127之間的時(shí)候,Integer會(huì)直接去常量池中選擇,那么當(dāng)你對(duì)2個(gè)在常亮池中的Integer的值進(jìn)行比較時(shí)候,它會(huì)表示這兩個(gè)Integer是指向同一個(gè)內(nèi)存地址.
public static Integer getIntegerExample2 = 127 ; public static Integer getIntegerExample_2 = 127; System.out.print("結(jié)果: "); System.out.println(getIntegerExample2 == getIntegerExample_2);
結(jié)果: true
相關(guān)視頻教程推薦:java視頻教程