Integer 中的缓存类 IntegerCache

我们先看一段代码:

public class TestAutoBoxing {
    public static void main(String[] args) {
        //-128到127之间
        Integer a=127;
        Integer b=127;
        System.out.println(a==b);
        Integer aa=128;
        Integer bb=128;
        System.out.println("aa==bb"+(aa==bb));
    }
}

再看看运行结果:

 

为什么会这样?

Integer 中的缓存类 IntegerCache

Cache 为[-128,127],IntegerCache 有一个静态的 Integer 数 组,在类加载时就将-128 到 127 的 Integer 对象创建了,并 保存在 cache 数组中,一旦程序调用 valueOf 方法,如果取 的值是在-128 到 127 之间就直接在 cache 缓存数组中去取 Integer 对象,超出范围就 new 一个对象。 

内容
原文地址:https://www.cnblogs.com/eyjdbk/p/11045707.html