一、概念描述
Java中128陷阱是指两个Integer对象直接用==判定 在某个范围内返回为true;
-引用类型用==判定 就是判定的两个对象是不是地址一样
-在Integer中范围-128~127的数值,有一个固定的地址(cache数组),在这个范围内的数值用==比较时相等的
二、实例
上图中前两个结果是基本类型和包装类型相比的,这个时候Integer类型的数据进行了自动拆箱,成基本数据,所以两者比较的结果相同。(拆箱的性能比较好,因为装箱要new一个新对象)
插入:
①什么是基本类型,什么是包装类型
基本类型:int,short,long,double,byte,boolean,float,char--------八大基本类型
包装类型:Integer,Short,Long,Double,Byte,Boolean,Float,Character--------包装类型
②什么是自动拆箱,自动装箱
自动拆箱:Java自动将封装器(对象)类型转换为基本类型的过程。
自动装箱:Java自动将原始类型值转换为对应的对象。
从源码角度分析128陷阱
我们可以看到在i>=IntegerCache.low&&i<=IntegerCache.high时是从cache数组里取得值,如果不在这个范围内,就是返回了一个新new的对象,这样若用==判断时,他们地址不同。
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;
}
可以发现,只要Integer类第一次被使用到,Integer的静态内部类就被加载,加载的时候会创建-128到127的Integer对象,同时创建一个数组cache来缓存这些对象,当使用valueOf()方法创建对象时,就直接返回已缓存的对象,也就是说不会再建新对象;当使用new关键字或者使用valueOf()方法创建小于-128或者大于127的值对象时,就会创建新对象。
new出来的对象是在堆中开辟了新地址,所以地址不相同,而根据源码分析valueOf创建的对象在-128~127时是有一个cache数组存储的,也就是我们常说的128陷阱。