歡迎您光臨本站 註冊首頁

JAVA Integer類型自加實例詳解

←手機掃碼閱讀     zmcjlove @ 2020-06-05 , reply:0

JAVA語言中有一些基本數據類型,比如int,long,double...
 

這些數據類型可以支持一些運算操作符,其中對於int類型的++/--操作符
 

Integer類型是一個對象類型,居然也可以支持++運算,那麼問題來了

一個Integer對象執行++操作之後還是原來那個對象嗎?
 

測試代碼
 

  public class IntegerTest {      @Test    public void test() {      Integer a = 1;      System.out.println(System.identityHashCode(a));      a++;      System.out.println(System.identityHashCode(a));    }  }

 

輸出
 

105704967
 392292416
 

對象的內存地址不一致,說明Integer對象執行++操作之後是返回一個新的Integer對象
 可以通過查看彙編代碼分析一下原因

簡化代碼
 

  public class IntegerTest {    public void test() {      Integer a = 1;      a++;    }  }

 

上述代碼的字節碼
 

  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  }

 

關於Java字節碼的介紹可以看一下這篇博客
 

我們主要關注8、13兩行,底層使用了java/lang/Integer.intValue拆箱,然後自加,再通過java/lang/Integer.valueOf裝箱,拆箱裝箱操作之後變量a 所指向的對象就不是原來的對象了


[zmcjlove ] JAVA Integer類型自加實例詳解已經有227次圍觀

http://coctec.com/docs/java/show-post-237059.html