项目中两个Integer类型数据在使用==比较时偶尔会出现错误的结果。明明两个整数值相等,但是结果却为false。丈二的和尚摸不着头脑呀。后来通过查阅资料才明白,以下是整理的内容,供以后查阅。
Java的Integer对象有个私有静态内部类IntegerCache,将-128至127之间整数提前实例化了。
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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() {}
}
当Integer类型数据在-128至127之间使用==比较时,直接返回固定的对象引用,是同一个,结果为true。但对于不在这区间的数字是在堆中new出来的。所以地址空间不一样,也就不相等。源码如下:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
那么该如何比较两个Integer类型数据呢?可以使用integer的intValue()、equals()、compareTo()等方法。
package com.lyf.test;
public class Test {
public static void main(String[] args) {
/**
* 一、integer在-128至127之间使用==进行比较
*/
Integer a1 = 123;
Integer b1 = 123;
System.out.println("一:" + (a1 == b1));
/**
* 二、integer不在-128至127之间使用==进行比较
*/
Integer a2 = 1230;
Integer b2 = 1230;
System.out.println("二:" + (a2 == b2));
/**
* 三、使用integer的intValue(),以 int 类型返回该 Integer 的值进行==比较
*/
Integer a3 = 1230;
Integer b3 = 1230;
System.out.println("三:" + (a3.intValue() == b3.intValue()));
/**
* 四、使用integer的equals(),比较此对象与指定对象。当且仅当参数不为 null,并且是一个与该对象包含相同 int 值的 Integer 对象时,结果为 true
*/
Integer a4 = 1230;
Integer b4 = 1230;
System.out.println("四:" + (a4.equals(b4)));
/**
* 五、使用integer的compareTo(),在数字上比较两个 Integer 对象,如果相等返回0
*/
Integer a5 = 1230;
Integer b5 = 1230;
System.out.println("五:" + (a5.compareTo(b5)));
}
}
结果:
一:true
二:false
三:true
四:true
五:0