Java基本類型作為局部變量和成員變量時的存儲方式有何不同?
問題描述
1、這個問題可能涉及到很多方面,我自己研究了一下,弄懂了一部分,但是有一部分還不清楚。先貼代碼(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個輸出與第8個輸出比較清楚。這是由于在Java堆中有一個用于存儲 常用基本數據類型字面量 的常量池,這個常量池可以存儲整型(-128到127),布爾型(沒有double類型)。執行“Integer abd1=127”時,除了在堆中建立一個值為127的Integer對象外,還會在相應的常量池中存儲一個127,然后,將這個Integer對象與常量池中的127關聯起來;再執行“Integer abf1=127”時,除了創建對象外,同樣將其與常量池中的127關聯起來,因而比較二者返回的是true。128就不同了,由于超出了常量池的存儲范圍,比較的僅僅是兩個Integer引用i1與i2,所以返回的是false。
3、我的問題是:對象成員變量中的int類型(非static,非final)是怎樣存儲的。也就是說,當新建一個Text對象t時,abc1(abc2與此類似)是直接存在棧里還是包裝后存在堆里,為什么會出現1-3(或5-7)返回是“true,false,true”的情況。
問題解答
回答1:一 int和Integer比較時,Integer會自動拆箱后與int比較二 對象實例變量分配在堆上1和5比較 由于Integer類型自動拆箱所以為truenew Integer(xxx) xxx即使在緩存范圍之內也會建立新的對象 所以2是false
相關文章:
1. javascript - 手機點擊input時,button會被頂上去?求解決!!!2. 百度地圖api - Android 百度地圖 集成了定位,導航 相互的jar包有沖突?3. python - django 按日歸檔統計訂單求解4. 網頁爬蟲 - python爬蟲用BeautifulSoup爬取<s>元素并寫入字典,但某些div下沒有這一元素,導致自動寫入下一條,如何解決?5. javascript - vue-mint UI - icon在哪里有文檔?6. HTML5禁止img預覽該怎么解決?7. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風格檢查怎么辦。。。8. html5 - 表單無法屏蔽自動填充 autocomplete=off9. html - 請教一個前端css問題。10. 請教一個python字符串處理的問題?
