我在知乎上看到这个问题以及这个问题的解析,于是上网查了资料以及去java查看源码,做了以下简单的解析。
public static void test1() {
Integer a = 1; // 等价于 Integer a = valueOf(1)
Integer b = 1;
System.out.println(a == b); // true
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true
}
对于以上的结果,首先查看java帮助手册中,对Interger的valueOf(int i)是这么描述的:
理解上就是这样:在一定的范围[-128,127]中,对Integer的赋值操作(整形赋值)是直接通过调用valueOf(int i)的方法的。而接下来看看valueOf(int i),这里讲到了如果在大于low小于high的范围中,会直接使用cache中已经创建的实例,而超出这个范围的才会重新创建新的实例:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里涉及到了IntegerCache.class这个类:
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;
}
因此,进行Integer对象相等性比较的时候,不能直接使用 == (比较的是对象的hashcode,只有[low,high]之间的Integer是相同的), 而应该使用equals方法。
英文原文:
https://dzone.com/articles/why-1000-1000-returns-false-but-100-100-returns-tr
译文链接:
http://www.codeceo.com/article/why-java-1000-100.html
文章的知乎专栏:
https://zhuanlan.zhihu.com/p/25421272
Interger文章:
http://www.importnew.com/18884.html