前段时间看到一个很有趣的例子:
public static void main(String[] args) {
Integer a = 18;
Integer b = 18;
Integer c = 200;
Integer d = 200;
System.out.println(a == b);
System.out.println(c == d);
}
打印结果为
true
false
非常有趣,为什么两个都为18的Integer判定==为true,而两个都为200的Integer判定==为false?
首先,直接将一个基本类型整数赋值给Integer,编译器会帮助我们自动装箱,所以
Integer a = 18;
相当于
Integer a = Integer.valueOf(18);
进入到valueOf()方法内部一探究竟
/**
* 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有一个内部类IntegerCache,如果Integer的值在-128~127之间,那么会直接获取这个IntegerCache,如果不在-128~127之间,才会去new一个Integer实例。
/**
* 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() {}
}
IntegerCache内部维护了一个Integer数组,然后在静态代码块中初始了值为-128~127之间的Integer,所以通过Integer.valueOf()方法返回的值为-128~127之间的Integer实际上都是同一个实例。同时我们注意到的是这个范围并不是完全固定的,范围的上界可以通过这个参数指定:
-XX:AutoBoxCacheMax
在idea中添加虚拟机参数
再次运行程序,打印结果为
true
true
这也告诉了我们一个道理,判断两个基本类型的包装类(或者String)是否相等时,不可以直接用==判断,而是要用equals()方法。
同时,在其他基本类型的包装类中,如Long,Byte,Short,Character中也有同样的设计。