Integer==Integer出现的问题
场景描述:
从DB取出数据封装到对象中, 对象的字段属性为Integer, 在对比2个对象的相同属性值是否相等时, 采用了"=="对比
结果:
方法执行后,并不会执行条件内的代码.
示例code:
T_channel t_channel = new T_channel();
t_channel.setBilingual(300);
T_channel t_channelNew = new T_channel();
t_channelNew.setBilingual(300);
//false
System.out.println(t_channelNew.getBilingual()==t_channel.getBilingual());
错误原因:
Integer是包装类型,简单的说他就是个Obj , 内部实现了一个缓存池数值范围为: -128~127. 如果数值超过127, 则会new Integer对象.
解决办法:
在对比对象的数值型属性值时, 外部包装一层方法, 使其对比真正的值.
示例code:
if(Integer.parseInt(t_channel.getBilingual().toString())==Integer.parseInt(t_channelNew.getBilingual().toString())){
System.out.println("hi");
}
问题的根源
源码code:
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);
}
cachecode:
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++);
}

浙公网安备 33010602011771号