java integer 相加_JAVA Integer类型自加

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."":()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字节码的介绍可以看一下这篇博客

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."":()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字节码的介绍可以看一下这篇博客
经验分享 程序员 微信小程序 职场和发展