zoukankan      html  css  js  c++  java
  • 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."<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 所指向的对象就不是原来的对象了

  • 相关阅读:
    Navicat连接MySQL数据库的一些问题与解决方案
    从select机制谈到epoll机制
    关于VS2017提示I/O文件操作函数需要加上_s的解决办法
    LeetCode初级算法(树篇)
    LeetCode初级算法(动态规划+设计问题篇)
    LeetCode初级算法(其他篇)
    Leetcode初级算法(排序和搜索+数学篇)
    Leetcode初级算法(链表篇)
    Leetcode初级算法(字符串篇)
    机器学习之k-近邻算法
  • 原文地址:https://www.cnblogs.com/migoo/p/12975512.html
Copyright © 2011-2022 走看看