在java中,我们通常使用到的是Integer和Long,经常做数据之间的比较,如
Integer i=10;
integer j=10;
if(i==j){
System.out.println(i==j);
}
这里输出是true
但是
Integer i=200;
integer j=200;
if(i==j){
System.out.println(i==j);
}
这里输出就是false
为什么呢?
看看源码中
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);
}
这里有个cache 如果范围是在-128~127之间,是直接从java.lang.Integer类中,直接取cache的地址,这里我们看待Integer i=100时,实际上是执行的Integer i=Integer.valueOf(100);那么可想而知的结果就是指向的是cache数组中值为100的地址,那么直接进行==操作符的比较,是相等的。
Long也存在相同的情况
那么我们如果是需要比较数值的情况下,尽量使用intValue()进行比较,或者compareTo函数进行比较,或者使用equal进行比较