看如下代码:

public class Test {
    public static void main(String[] args) {
        
        Integer i1 = 128; 
        Integer i2 = 128; 
        System.out.println(i1 == i2); //false
       
        Integer i3 = 127;
        Integer i4 = 127;
        System.out.println(i3 == i4); //true
    }
}

自动装箱,再底层实际调用的是这个方法Integer i1 = Integer.valueOf(128); 查看valueOf()方法的源码!

  其中IntegerCache是Integer类中的静态内部类,low和high是IntegerCache类中的静态常量.low是-128,high是127,cache是IntegerCache类中一个长度固定为256的数组.即IntegerCache.cache[255].也就是上面的代码可以写成这样的!

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

不在-128到127这个区间范围内的数字就会执行return new Integer(i);此时就会重新new对象,一旦new对象,那么就会在堆中分配相对应的空间.那么其地址值必定不相等!


 而在-128-127之间的数字就会执行 return Integer.IntegerCache.cache[255];IntegerCache类中有一个静态代码块,当内部类一加载,静态代码块就会执行.下面是IntegerCache类中的代码.

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() {}
    }

这么多的代码的核心就是 这里面有一个cache数组用来装新创建的对象的.在-128-127之间的数字都会将对象放入到这个固定cache数组中!而这个数组在堆内存中的地址是不会变的!所以在这个范围内的数字的地址值是相同的!


总结一下!

数字如果大于127或者小于-128,那么俩个对象的地址值不相等,如果小于等于127或者大于等于-128,那么这俩个对象的地址值是相等的!

(小编也在努力学习更多哟!以后再慢慢分享的啦!)

希望对友友们有所帮助!!!!