java---------128陷阱
public class Test {
public static void main(String []agrs) {
Integer a=100;
Integer b=100;
System.out.println(a==b);
a=1000;
b=1000;
System.out.println(a==b);
}
}
第一个会输出true,而第二个会输出false,这是为什么呢?
在Java中有一个128陷阱,当数据的绝对值小于某个值时,在进行比较时java会自动进行拆箱操作,但是当数据的绝对值大于这个值时,就不会进行自动拆箱操作了,需要我们进行手动拆箱
Integer a = 100;
Java会自动将上面的这句话转化为下面的这句
Integer a = Integer.valueOf(100);
但是当超过某个值时就需要我们手动执行valueOf()这个方法了
我们来看看valueOf()方法里都有什么
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
显然,当i >= IntegerCache.low && i <= IntegerCache.high时,会返回cache数组中现有的Integer对象,但是当不满足这个条件时就会创建一个新的Integer对象
IntegerCache.low、IntegerCache.high这两个东西又是什么呢?
接下来我们来看看IntegerCache这个类里都有什么
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
VM.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
刚刚我们一直在说某个值,那么这个值是什么呢,这里就有了答案,我们看到最低数值等于-128,而最大数值等于127,所以当数值在这个范围里面的时候,就会直接返回cache数组中现有的Integer对象,但是当数值不在这个范围里面就会创建一个新的对象
而我们知道,==比较的是内存地址,如果直接返回cache数组中的对象,那么就会是同一个内存地址,但是如果是新创建的对象,就会有不同的内存地址
就像下面这样
这样大家就明白了吧