Integer的一个小问题

本文探讨了 Java 中 Integer 对象在特定范围内被缓存的行为。当 Integer 的值位于-128到127之间时,它们会被视为同一对象,而超出此范围则会创建新对象。文章通过分析 Integer 的源码揭示了这一机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看面试题的时候看到这道题:

public class Demo {
    public static void main(String[] args) {
        Integer i1 = 128;
        Integer i2 = 128;
        System.out.println((i1.equals(i2)));
        System.out.println((i1==i2));
        Integer i3 = 100;
        Integer i4 = 100;
        System.out.println((i3.equals(i4)));
        System.out.println((i3==i4));
    }
}

这运行出来是:

true
false
true
true

从这个结果可以知道,i1和i2不是同一个对象,而i3和i4会是同一个对象。

那么可以从哪里下手呢?

可以从Integer的源码里面找到答案:

 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

如果传入的参数i的值在一个范围里面,那么就先改造一下这个参数然后返回回去,如果超过了这个范围就创造一个新的Integer对象。

那么先来看一下这个范围是什么。

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

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

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

可以知道,IntegerCache.low是直接定义好的了,就是-128,但是IntegerCache.high还需要再经过一定的流程来决定,一般来说应该是一个大于或等于127的数。

 

综上所述,一般来说,Integer创建的对象的值如果是在[-128,127]之内的,创建的值是相同的对象那就是同一个对象(当然如果值在后续操作改变了那就不是同一个对象了);但是如果是在这个范围之外的话,Integer对象就会创建新的对象。

转载于:https://www.cnblogs.com/NYfor2018/p/9482390.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值