Integer对象大小比较问题
一、问题
先来看一看例子
public class IntegerTest {
public static void main(String[] args) throws Exception {
Integer a1 = 127;
Integer b1 = Integer.valueOf(127);
System.out.println("1:"+(a1 == b1));
Integer a2 = 127;
Integer b2 = 127;
System.out.println("2:"+(a2 == b2));
Integer a3 = 128;
Integer b3 = 128;
System.out.println("3:"+(a3 == b3));
Integer a4 = 127;
Integer b4 = new Integer(127);
System.out.println("4:"+(a4 == b4));
}
}
答案是true、true、false、false
二、分析
答案1:基本类型和包装类直接互相转换时会触发装箱拆箱操作,所以Integer b2 = 127等于Integer b1 = Integer.valueOf(127)
答案23:比较127的时候是true,比较128的时候缺变成false了,查看Integer.valueOf()的代码:
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果数字的大小在范围内,会直接从缓存中取,如果大于范围就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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
查看IntegerCache代码发现下限是-128固定了,上限默认127,可以通过-Djava.lang.Integer.IntegerCache.high=1000参数调整
答案4:127和new Integer(127)直接用==比较,实际上是比较两个对象的地址,结果是false
三、结论
Integer对象正确的比较大小方法需要用equals()方法:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
Integer的equals方法重写了object里的equals,调用了intValue,比较两个对象的值

浙公网安备 33010602011771号