也是在道友的面经中看到这个问题,然后去查了一下,也自己去看了源码核实了一下,看的源码版本是jdk1.8,以此做个记录
创建长整型的包装类Long的实例时,可以是
Long a = 100L;//自动装箱
Long b = Long.valueOf(100L);//静态方法
Long c = new Long(100L);//构造器
我们用“==”来判断一下几个对象
Long a = 100L;
Long b = Long.valueOf(100L);
Long c = new Long(100L);
System.out.println(a==b);//true
System.out.println(a==c);//false
System.out.println(b==c);//false
但是如果将100L修改为128L,结果却是
Long a = 128L;
Long b = Long.valueOf(128L);
Long c = new Long(128L);
System.out.println(a==b);//false
System.out.println(a==c);//false
System.out.println(b==c);//false
这里区别在于100L的时候a、b是同一个实例,而128L的时候a、b不是同一个实例,我们去翻一下Long的源码,找到这个valueOf方法
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
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);
}
}
可见这里有这么一个static final的数组,是在静态代码块里初试化的,如果这个数字的范围是在-128——127之间,就不会调用构造器,而是返回这个数组里的对象,所以得到的会是同一个对象,“==”结果为true。
对于Integer类,也有类似的做法,也看一下valueOf 这部分的源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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) {
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;
}
private IntegerCache() {}
}
不同的是Integer缓存的下界是-128,上界是可以通过jvm参数-XX:AutoBoxCacheMax=size指定,取指定值与127的最大值并且不超过Integer表示范围,如不指定那就是127了。
JDK的设计上有很多细节,也可以理解为很多坑,如果没有仔细的研究过你正在使用的JDK类的话,可能很难理解你所遇到的问题,致自己。