1、new 无疑会调用构造方法,指定内存中新开辟的空间,两个Integer不是同一个实例对象。又 == 判断的是引用,所有会返回false。但equals重写了,比较的是值,所以返回的是true。源码如下
public int intValue() {
return value;
}
public Integer(int value) {
this.value = value;
}
public Integer(int value) {
this.value = value;
}
private final int value;
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
2、= 创建
Integer中的静态内部类 IntegerCache,缓存。
Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这相当于调用 valueOf 方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)]; //溢出计算,得到的对应索引
return new Integer(i); //不在-128~127的,都是创建的新对象
}
public static final int MAX_VALUE = 0x7fffffff;//2147483647对应的16进制数
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));
}
high = h; // high=127
cache = new Integer[(high - low) + 1]; // cache =new Integer[256];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); //提前把 -128~127的实例对象实例化好了,所以怎么取都是同一个
}
private IntegerCache() {}
}
总结:Integer赋值时,只要是new的,肯定是一个新对象;而 = 赋值的话,范围在 -128~127,就是同一个对象;超出范围都是新对象。
equals比较的是值是否相等。
Long类型 也缓存了 -128~127
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
Short类型 也缓存了 -128~127
private static class ShortCache {
private ShortCache(){} static final Short cache[] = new Short[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Short((short)(i - 128));
}
}