Java基本類型作為局部變量和成員變量時(shí)的存儲方式有何不同?
問題描述
1、這個(gè)問題可能涉及到很多方面,我自己研究了一下,弄懂了一部分,但是有一部分還不清楚。先貼代碼(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、先說自己清楚的部分:第4個(gè)輸出與第8個(gè)輸出比較清楚。這是由于在Java堆中有一個(gè)用于存儲 常用基本數(shù)據(jù)類型字面量 的常量池,這個(gè)常量池可以存儲整型(-128到127),布爾型(沒有double類型)。執(zhí)行“Integer abd1=127”時(shí),除了在堆中建立一個(gè)值為127的Integer對象外,還會(huì)在相應(yīng)的常量池中存儲一個(gè)127,然后,將這個(gè)Integer對象與常量池中的127關(guān)聯(lián)起來;再執(zhí)行“Integer abf1=127”時(shí),除了創(chuàng)建對象外,同樣將其與常量池中的127關(guān)聯(lián)起來,因而比較二者返回的是true。128就不同了,由于超出了常量池的存儲范圍,比較的僅僅是兩個(gè)Integer引用i1與i2,所以返回的是false。
3、我的問題是:對象成員變量中的int類型(非static,非final)是怎樣存儲的。也就是說,當(dāng)新建一個(gè)Text對象t時(shí),abc1(abc2與此類似)是直接存在棧里還是包裝后存在堆里,為什么會(huì)出現(xiàn)1-3(或5-7)返回是“true,false,true”的情況。
問題解答
回答1:一 int和Integer比較時(shí),Integer會(huì)自動(dòng)拆箱后與int比較二 對象實(shí)例變量分配在堆上1和5比較 由于Integer類型自動(dòng)拆箱所以為truenew Integer(xxx) xxx即使在緩存范圍之內(nèi)也會(huì)建立新的對象 所以2是false
相關(guān)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問4. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?5. 實(shí)現(xiàn)bing搜索工具urlAPI提交6. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?7. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化8. phpstudy8.1支持win11系統(tǒng)嗎?9. 配置Apache時(shí),添加對PHP的支持時(shí)語法錯(cuò)誤10. css - 寫頁面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~

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