本文简单分析了下Integer类型的==比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals。
先看下这段代码,然后猜下结果:
Integer i1 = 50;
Integer i2 = 50;
Integer i3 = 128;
Integer i4 = 128;
System.out.println(i1 == i2);
System.out.println(i3 == i4);
针对以上结果,估计不少Java小伙伴会算错!
如果在项目中使用==对Integer进行比较,很容易掉坑。
为什么发生以上结果?
1.执行Integer i1 = 50的时候,底层会进行自动装箱:
Integer i1 = 50;
//底层自动装箱
Integer i = Integer.valueOf(50);
2.再看==操作
==是判断两个对象在内存中的地址是否相等。所以System.out.println(i1 == i2);和System.out.println(i3 == i4);是判断他们在内存中的地址是否相等。
根据猜测应该全是false或者全是true呀,怎么会不同呢?
3.源码底下无秘密
通过翻看jdk源码,你会发现:如果要创建的 Integer 对象的值在 -128 到 127 之间,会从 IntegerCache 类中直接返回,否则才调用new Integer方法创建。所以只要数值是正的Integer > 127,则会new一个新的对象。数值 <= 127时会直接从Cache中获取到同一个对象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
结论
本文简单分析了下Integer类型的==比较,解释了为啥结果不一致,所以今后碰到Integer比较的时候,建议使用equals。
同理,Byte、Shot、Long等,也有Cache,各位记得翻看源码!
©本文为清一色官方代发,观点仅代表作者本人,与清一色无关。清一色对文中陈述、观点判断保持中立,不对所包含内容的准确性、可靠性或完整性提供任何明示或暗示的保证。本文不作为投资理财建议,请读者仅作参考,并请自行承担全部责任。文中部分文字/图片/视频/音频等来源于网络,如侵犯到著作权人的权利,请与我们联系(微信/QQ:1074760229)。转载请注明出处:清一色财经