public static void main(String[] args) {
Integer a = 128;
Integer b = 128;
System.out.println(a == b);
Integer c = 127;
Integer d = 127;
System.out.println(c == d);
}
打印出来结果是什么呢 ?
第一个是fasle;第二个是true;
为什么会这样呢?
我们先来看看Integer的封装吧。
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
当你直接给一个Integer对象一个int值的时候,其实它调用了valueOf方法。当你的值在-128~~~127之间时,它返回的是 IntegerCache.cache[i + offset];,让我们在看看 IntegerCache.cache[i + offset]这个数组吧。
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
这个数组的长度为256,保存的是-128~~~127之间的数据,所以在这个范围内的数据是不会new新对象的,不在这个范围内,才返回 return new Integer(i);
所以一个为false,第二个为true。其实也可以这么理解,在内存中,存在整形数据池,只是他的范围是-128~~~127,当你给的数据在这个范围内,它直接从数据池中拿数据,不用new。超过这个范围才去new。
一个有趣的问题:关于Java中的Integer
最新推荐文章于 2022-03-28 17:30:09 发布