測試代碼:
public class IntegerTest {
public static void main(String[] args) {
Integer i1 = 12;
Integer i2 = 12;
Integer i3 = 135;
Integer i4 = 135;
System.out.println("i1 == i2? " + (i1 == i2));
System.out.println("i3 == i4? " + (i3 == i4));
}
}
輸出結果:
i1 == i2? true
i3 == i4? false
為什么都是Integer類的對象會輸出不同的結果呢?
是因為Integer類的內部做了緩存處理,在Integer內部有一個IntegerCache的靜態內部類,該內部類中會緩存-128到127的整數。當用一個int類型的變量給Integer時,會使用自動裝箱的程序。
public final class Integer extends Number implements
Comparable<Integer> {
...
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
...
cache = new Integer[(high-low)+1];
int j = low;
for(int k = 0;k < cache.length;k ++)
cache[k] = new Integer(j++);
...
}
...
//自動裝箱的程序
public static Integer valueOf(int i) {
if(i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i+(-IntegerCache.low)];
return new Integer(i);
}
...
}
為了進一步深入地理解Integer中的玄機,可以增加一下難度,使用synchronized關鍵字進一步驗證。
public class ThreadA {
static Integer integer = 8;
public static void main(String[] args) throws InterruptedException{
ThreadB b =new ThreadB();
b.start();
synchronized (integer) {
System.out.println("deng dui xiang b wan cheng b wan
cheng ....");
integer.wait();
System.out.println("b dui xiang zong he shi :" + b.total);
}
}
}
class ThreadB extends Thread {
int total;
Integer integer = 8;
@Override
public void run() {
synchronized (integer) {
for(int i = 0;i < 101;i ++) {
total += i;
}
integer.notify();
System.out.println("computing is finished");
}
}
}
輸出結果
deng dui xiang b wan cheng b wan cheng ....
computing is finished
b dui xiang zong he shi :5050
程序中兩處使用Integer類的對象作為監視器,兩個Integer的對象都是分別new出來的,但是仍然可以實現兩個線程的通信,所以從從此也可以判斷出Integer內部是使用cache的機制。