JAVA Integer類型自加實(shí)例詳解
JAVA語言中有一些基本數(shù)據(jù)類型,比如int,long,double...
這些數(shù)據(jù)類型可以支持一些運(yùn)算操作符,其中對于int類型的++/--操作符
Integer類型是一個對象類型,居然也可以支持++運(yùn)算,那么問題來了
一個Integer對象執(zhí)行++操作之后還是原來那個對象嗎?
測試代碼
public class IntegerTest { @Test public void test() { Integer a = 1; System.out.println(System.identityHashCode(a)); a++; System.out.println(System.identityHashCode(a)); }}
輸出
105704967392292416
對象的內(nèi)存地址不一致,說明Integer對象執(zhí)行++操作之后是返回一個新的Integer對象可以通過查看匯編代碼分析一下原因
簡化代碼
public class IntegerTest { public void test() { Integer a = 1; a++; }}
上述代碼的字節(jié)碼
Compiled from 'IntegerTest.java'public class com.migoo.common.IntegerTest { public com.migoo.common.IntegerTest(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object.'<init>':()V 4: return public void test(); Code: 0: iconst_1 1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 4: astore_1 5: aload_1 6: astore_2 7: aload_1 8: invokevirtual #3 // Method java/lang/Integer.intValue:()I 11: iconst_1 12: iadd 13: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 16: dup 17: astore_1 18: astore_3 19: aload_2 20: pop 21: return}
關(guān)于Java字節(jié)碼的介紹可以看一下這篇博客
我們主要關(guān)注8、13兩行,底層使用了java/lang/Integer.intValue拆箱,然后自加,再通過java/lang/Integer.valueOf裝箱,拆箱裝箱操作之后變量a 所指向的對象就不是原來的對象了
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php bugs代碼審計(jì)基礎(chǔ)詳解2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. xml中的空格之完全解說4. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……5. XML入門的常見問題(四)6. ASP中if語句、select 、while循環(huán)的使用方法7. ASP使用MySQL數(shù)據(jù)庫的方法8. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享9. WMLScript的語法基礎(chǔ)10. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法
