Java基本類型作為局部變量和成員變量時(shí)的存儲(chǔ)方式有何不同?
問(wèn)題描述
1、這個(gè)問(wèn)題可能涉及到很多方面,我自己研究了一下,弄懂了一部分,但是有一部分還不清楚。先貼代碼(Java版本1.8):
public class Test{ int abc1 = 127; Integer abd1 = 127; Integer abf1 = 127; Integer abe1 = new Integer(127); {System.out.print('1t');System.out.println(abc1==abd1);System.out.print('2t');System.out.println(abd1==abe1);System.out.print('3t');System.out.println(abc1==abe1);System.out.print('4t');System.out.println(abd1==abf1); } int abc2 = 128; Integer abd2 = 128; Integer abf2 = 128; Integer abe2 = new Integer(128); {System.out.print('5t');System.out.println(abc2==abd2);System.out.print('6t');System.out.println(abd2==abe2);System.out.print('7t');System.out.println(abc2==abe2);System.out.print('8t');System.out.println(abd2==abf2); } public static void main(String[] args){Test t =new Test(); }/*輸出為:1 true2 false3 true4 true5 true6 false7 true8 false*/}
2、先說(shuō)自己清楚的部分:第4個(gè)輸出與第8個(gè)輸出比較清楚。這是由于在Java堆中有一個(gè)用于存儲(chǔ) 常用基本數(shù)據(jù)類型字面量 的常量池,這個(gè)常量池可以存儲(chǔ)整型(-128到127),布爾型(沒有double類型)。執(zhí)行“Integer abd1=127”時(shí),除了在堆中建立一個(gè)值為127的Integer對(duì)象外,還會(huì)在相應(yīng)的常量池中存儲(chǔ)一個(gè)127,然后,將這個(gè)Integer對(duì)象與常量池中的127關(guān)聯(lián)起來(lái);再執(zhí)行“Integer abf1=127”時(shí),除了創(chuàng)建對(duì)象外,同樣將其與常量池中的127關(guān)聯(lián)起來(lái),因而比較二者返回的是true。128就不同了,由于超出了常量池的存儲(chǔ)范圍,比較的僅僅是兩個(gè)Integer引用i1與i2,所以返回的是false。
3、我的問(wèn)題是:對(duì)象成員變量中的int類型(非static,非final)是怎樣存儲(chǔ)的。也就是說(shuō),當(dāng)新建一個(gè)Text對(duì)象t時(shí),abc1(abc2與此類似)是直接存在棧里還是包裝后存在堆里,為什么會(huì)出現(xiàn)1-3(或5-7)返回是“true,false,true”的情況。
問(wèn)題解答
回答1:一 int和Integer比較時(shí),Integer會(huì)自動(dòng)拆箱后與int比較二 對(duì)象實(shí)例變量分配在堆上1和5比較 由于Integer類型自動(dòng)拆箱所以為truenew Integer(xxx) xxx即使在緩存范圍之內(nèi)也會(huì)建立新的對(duì)象 所以2是false
相關(guān)文章:
1. mac里的docker如何命令行開啟呢?2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?4. 關(guān)于docker下的nginx壓力測(cè)試5. docker容器呢SSH為什么連不通呢?6. nignx - docker內(nèi)nginx 80端口被占用7. 如何解決Centos下Docker服務(wù)啟動(dòng)無(wú)響應(yīng),且輸入docker命令無(wú)響應(yīng)?8. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個(gè)是怎么回事????9. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問(wèn)題。10. docker start -a dockername 老是卡住,什么情況?

網(wǎng)公網(wǎng)安備