Integer 是java5 引进的新个性

先上一个小试验:

 public static void main(String[] args) {        Integer a1 = 100;        Integer a2 = 100;        System.out.println(a1 == a2);        Integer b1 = 1000;        Integer b2 = 1000;        System.out.println(b1 == b2);    }后果:    truefalseProcess finished with exit code 0

先说论断,[-128,127] 这个区间 true ,其余的范畴为 new 一个新的对象。

剖析:

查看字节码

public static main([Ljava/lang/String;)V   L0    LINENUMBER 7 L0    BIPUSH 100    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;    ASTORE 1   L1    LINENUMBER 8 L1    BIPUSH 100    INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;    ASTORE 2                    …………

代码实际上是Integer.valueOf

    public static Integer valueOf(int i) {        //缓存在数组,相应对象间接返回        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        //不在缓存,则会new一个        return new Integer(i);    }

IntegerCache 是 Integer 的一个匿名外部类

这也是主动装箱的代码实现。

JAVA将根本类型主动转换为包装类的过程称为主动装箱(autoboxing)。

实际上在 Java 5 中引入这个个性的时候,范畴是固定的 -128 至 +127。

起初在Java 6 后,最大值映射到 java.lang.Integer.IntegerCache.high,能够应用 JVM 的启动参数设置最大值。(通过 JVM 的启动参数 -XX:AutoBoxCacheMax=size 批改)

缓存通过一个 for 循环实现。从小到大的创立尽可能多的整数并存储在一个名为 cache 的整数数组中。

这个缓存会在 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() {}    }

所有整数类型的类都有相似的缓存机制:

有 ByteCache 用于缓存 Byte 对象

有 ShortCache 用于缓存 Short 对象

有 LongCache 用于缓存 Long 对象

Byte,Short,Long 的缓存池范畴默认都是: -128 到 127。能够看出,Byte的所有值都在缓存区中,用它生成的雷同值对象都是相等的。

所有整型(Byte,Short,Long)的比拟法则与Integer是一样的。

同时Character 对象也有CharacterCache 缓存 池,范畴是 0 到 127。

除了 Integer 能够通过参数扭转范畴外,其它的都不行。

参考链接:

https://zhuanlan.zhihu.com/p/...
https://blog.csdn.net/maihilt...