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
所指向的對象就不是原來的對象了