java程序猿对Long和Integer不可谓不熟,但它们的有些秘密估计好多人都是不知道的,我们先从一个例子开始
public class LongTest {
public static void main(String[] args){
Long a = 10L;
Long b = 10L;
Long c = 127L;
Long d = 127L;
Long e = 128L;
Long f = 128L;
Long g = new Long(12);
Long h = new Long(12);
System.out.println(a == b); //true
System.out.println(c == d); //true
System.out.println(e == f); //false
System.out.println(g == h); //false
}
}
上面例子的运行结果正如代码注释,是不是有(xiao)点(xiao)惊(zi)呆(lian)了(xia),最后一个结果应该大家都能接受,前面看着是不是有点意料之外的意思,这就是今天我要告诉大家的小秘密。
上面这个问题是由于jdk 中Long缓存了-128~127之间的值,不多说了,上源码:
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
如果在Integer中遇到类似问题,同上解。
以上小小点心供各位客官品尝,不到之处望不吝赐教!