Interger值判断问题
在介绍Interger值判断的前我先问大家一个如下一个问题,请大家回答一下三个等值判断输出的结果,
Integer minA=-128;
Integer minAA=-128;
System.out.printf("minA=minAA? %s \n",minA==minAA)
Integer maxA=127;
Integer maxAA=127;
System.out.printf("maxA=maxAA? %s \n",maxA==maxAA)
Integer maxB=128;
Integer maxBB=128;
System.out.printf("maxB=maxBB? %s \n",maxB==maxBB)

输出结果为:
看看是不是全部回答对了,如果回答对了那么恭喜你,你已经了解Interger了不需要在往下看了!
minA=minAA? true
maxA=maxAA? true
maxB=maxBB? false
那么为什么会会出现这样的结果呢?
这是因为==只有在Java基本类型(short,int,long,byte,char,float,double,boolean)中比较的是值,其他类型中比较的是内存地址。因此,InteGer类中==比较的是内存地址,而不是值从而导致maxB和maxBB因为内存地址不相同导致maxB==maxBB不相同。
那么这到底是怎么回事呢?如果都是内存地址的比较,那么minA,maxA和maxB的判断结果都应该是false,为什么maxA==maxAA和minA==minAA这的比较回事true?
结果分析
这是因为Integer类在负128至127(默认)区间的Integer实例缓存到cache数组中,具体实现查看Integer源码。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return 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) {
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() {}
}
注意:这里的创建不包括用new创建,new创建对象不会复用缓存实例,以下代码的运行结果就可以得知
Integer maxC=126;
Integer maxCC=new Integer(126);
System.out.printf("maxC=maxCC? %s \n",maxC==maxCC);
结果:
maxC=maxCC? false
解决问题方案
推荐用equals(),这个还可以避免一些空指针问题的出现。
或者使用Integer.intValue();这样出来的就是int值,就可以直接比较了(可能会抛出空指针异常)
Byte、Short、Long、Character具有缓存机制的类
ByteCache用于缓存Byte对象,ShortCache用于缓存Short对象,LongCache用于缓存Long对象,CharacterCache用于缓存Character对象。这些类都有缓存的范围,其中Byte,Short,Integer,Long为 -128 到 127,Character范围为 0 到 127。除了 Integer 可以通过参数改变范围外,其它的都不行。例如设置Integer最大值为1000
-XX:AutoBoxCacheMax=1000
如图所示:
总结:
今天讲解了一下Integer中比较相等中容易出错的方式interA==interB,从底层分析了其原理,以及不相等的原因。
github地址:https://github.com/bangbangzhou/greemes/tree/master
谢谢关注

公众号





