缓存常量池

亚信面试题:

http://www.xuexila.com/mianshiti/1699798.html

先说结论
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);
}
}
---------------------
作者:大大大超人
来源:CSDN
原文:https://blog.csdn.net/superman4933/article/details/79293112
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/fengli9998/p/9809509.html