Integer 的-128至127缓存常量池记录

先说结论

Integer a=127;

Integer b=127;

Integer c=128;

Integer d=128;

a==b true
c==d false

Integer a=new Integer (127);

Integer b=new Integer (127);

Integer c=new Integer (128);

Integer d=new Integer (128);

a==b false
c==d false
Integer 内部有一个-128到127的缓存池,但是如果是new出来的,那每一个对象都会去新建,不会用到缓存池的数据
实测其他基本数据类型的包装类都有这个缓存池,包括:Byte,Short,Long

  public static Integer valueOf(int i) {
        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
    }

    /**
     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing
     */
    private static final Integer[] SMALL_VALUES = new Integer[256];

    static {
        for (int i = -128; i < 128; i++) {
            SMALL_VALUES[i + 128] = new Integer(i);
        }
    }

猜你喜欢

转载自blog.csdn.net/superman4933/article/details/79293112