走进Java:Integer128陷阱

发布于:2025-03-18 ⋅ 阅读:(14) ⋅ 点赞:(0)

❀❀❀  大佬求个关注~祝您开心每一天  ❀❀❀

目录

一、Integer和int的联系

1.1 Integer和int的区别

1.2 Integer和int的相互转换 

二、装箱

三、拆箱


今天在学习Java的时候遇到了下面几个问题。

public static void main(String[] args) {
        Integer num1 = 127;
        Integer num2 = 127;
        Integer num3 = 128;
        Integer num4 = 128;
        int num5 = 127;
        int num6 = 128;
        System.out.println(num1 == num2);
        System.out.println(num3 == num4);
        System.out.println(num1 == num5);
        System.out.println(num6 == num3);
    }

我会认为这个问题的输出结果是true、true、true、true。但是在运行的时候发现,结果并不是想象中的那样子。正确答案如下。

🌼一、Integer和int的联系

Java 5 引入了自动装箱(Autoboxing)和拆箱(Unboxing)机制,允许 int 类型和 Integer 类型之间进行自动转换。

  • 自动装箱:将 int 类型的值自动转换为 Integer 对象。
  • 自动拆箱:将 Integer 对象自动转换为 int 类型的值。

1.1 Integer和int的区别

1. 类型不同

  • int 是基本数据类型,直接存储整数值。

  • Integer 是引用类型,存储的是对象的引用,指向堆内存中的 Integer 对象。

2. 内存使用

  • int 变量在栈内存中直接存储整数值,占用的内存空间固定为 4 个字节。

  • Integer 对象存储在堆内存中,除了存储整数值外,还需要额外的内存来存储对象的元数据,因此占用的内存空间相对较大。

3. 空值处理

  • int 是基本数据类型,不能为 null

  • Integer 是引用类型,可以赋值为 null,这在某些需要表示 “无值” 的场景中非常有用。

1.2 Integer和int的相互转换 

在上一篇文章当中说到了类和对象,Integer并不是八大基本数据类型中的一个,Integer是一个类,类似于上一篇文章说到的学生类。

int转换为Intege:装箱

看下边一行代码。下边这行代码的执行涉及到了装箱操作。

Integer num1 = 127;

代码真正在执行的时候会变为下方的样子。这就是装箱操作,就是把一个基本类型的int变量,包装成一个引用类型的Integer变量。

Integer num1 = Integer.valueOf(127);

Integer转换为int:拆箱

下方的代码涉及到拆箱操作。

Integer num1 = 127;
int num2 = num1;

代码在执行的时候会变为这个样子。这就是拆箱操作。

Integer num1 = Ineger.valueOf(127);
int num2 = num1.intValue();

🍎二、装箱

想要知道最开始的问题,就要具体了解,装箱到底是如何实现的,为什么对127装箱作比较是true,对128装箱后作比较是false,现在来跟进装箱的代码。

跟进到源码当中,我们发现这个方法对于我们传入的数值还进行了一次判断,i要和IntegerCache的low和high作比较,如果在low和high之前,那么就返回一个值,否则的话就返回一个new出来的Integer对象。


IntegerCache.low

能够看到,low其实是一个值,大小为-128


IntegerCache.high

同样的,high也是一个值,只不过好像没有初始值,这里我们先看做127。

对于一开始的问题,我们传进来的值是127。

 Integer num1 = 127;
 Integer num2 = 127;

 那么就会返回这个值。

 return IntegerCache.cache[i + (-IntegerCache.low)];

 IntegerCache.cache其实是一个Integer数组,用于存储一些Integer类创建出的对象。

那么它可以有哪些对象呢?看如下代码。

static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            CDS.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

 这是一个静态初始块,现在不讲太多,只是Integer类加载的时候会执行里边的代码,在这里有对cache的初始化。我们只需要关注下边的部分。

            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;

size就是我们设置的(127 + 128) + 1,也就是256。cache初始化的过程如下。

  1. 根据low和high计算size
  2. 初始化一个size大小的Integer数组
  3. 对数组进行赋值操作,也就是数组的0~255索引为存储的是-128~127之间的数字(包括0)

现在我们已经知道了,cache就是一个已经初始化好的数组,里边存储了-128~127之间的Integer对象的引用。那么回到上访的代码。如果我们传入的值在low~high之间,那么就会直接从这个cache中拿取已经创建好的Integer变量。

 return IntegerCache.cache[i + (-IntegerCache.low)];

现在有一点明白了,如果直接拿取的是已经创建好的对象,是不是就意味着每次拿的时候获取的都是同一个对象呢?就是这样子。

Integer num3 = 128;
Integer num4 = 128;

 如果传入的是128。那么就会通过new的方式来创建Integer对象,每次new出来的是一个全新的对象,所以通过new方式创建的对象在怎么比较也是false,因为引用类型对象之间用==操作,比较的是两个对象的地址是否相同,也就是说num3和num4比较的是他们在内存空间的地址是否是相同的,并非比较的他们的内容是否都是128。

而num1和num2的比较其实也是比较地址,但是因为num1和num2指向的是同一个对象,所以就是true。


🌹三、拆箱

拆箱操作就很简单了,调用intValue()方法返回包装的整数。

public static void main(String[] args) {
        Integer num1 = 127;
        Integer num2 = 127;
        Integer num3 = 128;
        Integer num4 = 128;
        int num5 = 127;
        int num6 = 128;
        System.out.println(num1 == num2);  // Integer.valueOf(127) == Integer.valueOf(127)
        System.out.println(num3 == num4);  // Integer.valueOf(128) == Integer.valueOf(128)
        System.out.println(num1 == num5);  // num1.intValue() == 127
        System.out.println(num6 == num3);  // num2.intValue() == 128
    }

现在是否对这个问题了解的更多了一点呢。