Integer类型匹配项等的时候一定要用 equals() 方法!不要用 ==
这绝对是个大坑!
记得是有一次查询数据,数据封装到实体类进行数据匹配的时候,出现了Integer类型比较像等的问题,明明两个数是一样的,但是就是匹配不上。
一个很简陋的例子:
public static void main(String[] args) {
Integer a = 333;
Integer b = 333;
if (a == b){
System.out.println(true);
} else {
System.out.println(false);
}
}
结果输出:
明明是一样的数,结果没有匹配成功;
虽然Integer不用创建对象就能赋值数据,但是它始终是一个包装类
点进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 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() {}
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
等等源码...
意思就是当Integer的值为-128~127之间的值的时候,Integer直接把这些值放进常量池里面,这个时候,用 == 是可以比较的。
比如:
public static void main(String[] args) {
Integer a = -128;
Integer b = -128;
if (a == b){
System.out.println(true);
} else {
System.out.println(false);
}
}
结果输出:
但是当赋给Integer值超过这个范围的时候,Integer就会创建对象,值就不放在常量池里面了,这个时候再用 == 就不可以比较了,因为存放的位置都不一样了,数一样还是会返回false
所以Integer的话强烈建议用 equals() 这个方法!
public static void main(String[] args) {
Integer a = 2345;
Integer b = 2345;
if (a.equals(b)){
System.out.println(true);
} else {
System.out.println(false);
}
}
结果: