您的位置:首页 > 编程语言 > Java开发

【Java】Java中Integer和int比较大小出现的错误

2017-06-15 14:55 417 查看
Java的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() {}
}


范围在 -128 ~ 127 之间(包括),直接用==

Integer i = 100;
int j = 100;
return i == j;//true


这里返回的是true.

但是 >127 或者 <-128

Integer i = 500;
int j = 500;
return i == j; //false


所以当需要判断的Integer不在这个范围的时候,最好用parseInt()方法转换成int后再去比较大小
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: