Integer的相等比较
Integer的相等比较

Integer的相等比较
• 发表于 1年前
• 阅读 25
• 收藏 0
• 评论 0

Integer a1 = Integer.valueOf(60);  //直接比较
Integer b1 = 60;
System.out.println("1:="+(a1 == b1));

Integer a2 = 60;
Integer b2 = 60;
System.out.println("2:="+(a2 == b2));

Integer a3 = new Integer(60);    //自动装箱
Integer b3 = 60;
System.out.println("3:="+(a3 == b3));

Integer a4 = 129;
Integer b4 = 129;
System.out.println("4:="+(a4 == b4));

Integer a5 = new Integer(60);    //自动装箱
Integer b5 = new Integer(60);
System.out.println("5:="+(a5 == b5));

1:=true
2:=true
3:=false
4:=false
5:=false

jdk对-128 --127之间的数值设立了缓冲区，回去缓冲区读取数据，但是对于这个范围之外的数据没有缓冲区，所以第二个和第四个输出结果不一样，下面是jdk对于Integer源码这段的实现：

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 HighPropValue =
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() {}
}

public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

×