您的位置:首页 > 其它

Integer值比较的问题

2016-01-12 10:20 357 查看
最近开发中,遇到一个问题,两个Integer类型的值,进行比较时,明明两个值是相等的,但是用==比较却是false,结果这是一个很low的问题,记录一下

代码片段:

Integer a = 100;
Integer b = 100;
System.out.println("100 == 100 结果是:" + (a == b));
100 == 100 结果是:true


上面是正常的,打印结果是true,可是下面的代码段,就出现问题了

Integer a = 300;
Integer b = 300;
System.out.println("300 == 300 结果是:" + (a == b));
300 == 300 结果是:false


问题出现了,为什么Integer类型的300一样的值,比较却不相同呢? 我们看下源码里

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


这是jdk对Integer的复制,我们看到它对传进来的变量值做了一个判断,如果i>=-128 && i <= 127,他会从一个为cache的数组里直接取,那么我们在看看cache数组是什么

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;

// 先实例化了一个大小为 (127 + 128 + 1)这样大小的数组
cache = new Integer[(high - low) + 1];
int j = low;

// 循环往数组里赋值,赋的什么呢,就是一个Integer的对象
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() {}
}


所以,我们从上面可以得到,如果变量值在-127和128之间,他会直接从事先实例化好的数组里面取,==我们知道,比较的是堆里面的对象,从数组里取,肯定是一样的实例,所以为true;  但是如果不在这个范围内,他会重新 new Integer()对象,那对于Integer a = 300, Integer b = 300;实际是哪个等于 new了两个对象,这时候 == 比较,肯定是false

结论就是:如果是Integer封装类,比较值相等,我们尽量采用 equals()比较,因为equals比较的是值,所以不管是100,还是300,a.equals(b)都是true

                   如果是原始类型int,则可以用==比较
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: