我们先来看一段代码
Integer m = 127;
Integer n = 127;
System.out.println(m == n);
运行的结果返回true
Integer i = 128;
Integer j = 128;
System.out.println(i == j);
此时的返回结果false
只差了1,但为什么结果不一样,这涉及到了java的自动拆箱
.
因为Ingeter是int的包装类,Integer变量必须实例化后才能使用,实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象,常自动装箱拆箱;
说人话就是,装箱就是将基本数据类型转化为包装器类型,而拆箱则是将包装器类型转化为基本数据类型.
通过上述代码得到的不同结果,我们可以知道,介于 -128 ~ 127 之间的 int 被包装到固定的对象中 .
所以当m,n都等于127时m和n被包装在同一个对象中,因此是相等的.
而当m,n都等于128时m和n分别装在两个对象中,地址肯定是不相同的,所以用"=="去判断结果是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);
}
Integer m=128,用这种方式赋值,会调用valueOf函数,然后我们看一下IntegerCache源码
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) {
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);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
通过源码我们可以知道Integer将所有的在-128~127之间的整数都实例化了,所以当你创造属于这个范围内的Integer时,都会是这同一个对象.
那如果想避免128陷阱怎么办,用equals来比较就行了
会获取Integer的基本类型值进行比较
或者你可以
Integer m = 128;
int n = 128;
System.out.println(m == n);
输出的结果是true,因为Integer会自动拆箱为int进行比较.