这是一个挺有意思的讨论话题。但是却引出一个常见的面试题。
问题引出
如果你运行下面的代码:
Integer a = 1000, b = 1000;
System.out.println(a == b);//1
Integer c = 100, d = 100;
System.out.println(c == d);//2
你会得到:
false
true
基本知识
我们知道,如果两个引用指向同一个对象,用\==表示它们是相等的。如果两个引用指向不同的对象,用==表示它们是不相等的,即使它们的内容相同。因此,后面一条语句也应该是false 。
那么上面为什么会出现true的情况呢?咱们去看一下 Integer.java类,你会发现有一个内部私有类,IntegerCache.java,它缓存了从-128到127之间的所有的整数对象。
源代码
//内部类
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
//静态代码块对high进行赋值
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() {}
}
所以所有的小整数(-128-127)在内部缓存,然后当我们声明类似
Integer c = 100;
的时候,它实际上在内部做的是:
Integer i = Integer.valueOf(100);
现在,如果我们去看valueOf()方法,我们可以看到源代码中的实现:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果值的范围在-128到127之间,它就从高速缓存返回实例。
因此在:
Integer c = 100, d = 100;
中c和d指向了同一个对象指向了同一个对象。这就解释了上面答案为true的原因。
为什么这里需要缓存?
合乎逻辑的理由是,在此范围内的“小”整数使用率比大整数要高,因此,使用相同的底层对象是有价值的,可以减少潜在的内存占用。
然而,通过反射API你会误用此功能。
运行下面的代码,享受它的魅力吧
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0]; //1
Field myCache = cache.getDeclaredField("cache"); //2
myCache.setAccessible(true);//3
Integer[] newCache = (Integer[]) myCache.get(cache); //4
newCache[132] = newCache[133]; //5
int a = 2;
int b = a + a;
int c = a+b;
//但是在打印时由于做了装箱,int数据变成了Integer,这时会采用缓存,所以4就会打印出5来。
System.out.printf("%d + %d = %d", a, a, b); //
}
System.out.println(c);//输出6
考题:
//由于Java的自动装箱技术,相当于新建一个值为59的Java对象;
Integer i01 = 59;
//由于是基本数据类型,在栈中直接建立了变量59(比较的时候比较的是数值)与Integer比较时,会进行自动拆箱
int i02 = 59;
Integer i03 = Integer.valueOf(59);
//新建对象59
Integer i04 = new Integer(59);
System.out.println(i01 == i02);//true
System.out.println(i01 == i03);//true
System.out.println(i03 == i04);//false
System.out.println(i02 == i04);//true