简述128陷阱
一、什么是128陷阱
有如下代码
public static void main(String[] args) {
Integer a=100;
Integer b=200;
Integer a1=100;
Integer b1=200;
int a2=100;
int b2=200;
System.out.println(a==a1);
System.out.println(b==b1);
System.out.println(a==a2);
System.out.println(b==b2);
}
输出结果为:  问题:为什么b == b1为false呢,为什么b == b2又是true了?
二、原因
1、首先要了解Java中的自动装箱和拆箱机制 装箱就是自动将基本数据类型转换为包装器类型 拆箱就是自动将包装器类型转换为基本数据类型
Integer a=100;
int a3=a.intValue();
int b2=200;
Integer b3=Integer.valueOf(b2);
现在就可以解释为什么b == b2又是true了,就是因为编译器将Integer包装器类型自动转换成了基本类型,该过程不涉及运行。
2、那为什么b == b1为false呢? 首先要了解Integer包装类创建对象时的原则 打开Integer源码:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
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);
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
从源码可以看出,当我们创建一个Integer对象时,同时会创建一个cache数组,其中存储着-128到127的值:例
Integer a=100;
Integer a1=100;
a和a1指向的均为我们创建时事先创建好的cache数组中的100的位置,因此指向的地址是相同的,而“==”判断的是地址,所以返回值为true。
当我们创建的Integer对象的值大于127时,就会创建新的cache数组,每次定义新的对象均会创建新的cache数组,因此当定义
Integer b=200;
Integer b1=200;
此时,b和b1指向的地址是不同的即是不同的对象,因此用“==”判断时返回false
|