前言
這個幾乎是Java 5引入自動裝箱和自動拆箱后,很多人都會遇到(而且不止一次),而又完全摸不著頭腦的坑。雖然已有很多文章分析了原因,但鑒于我這次還差點坑了同學,還是紀錄下來長點記性。
問題描述
例一
來個簡單點的例子
public static void main(String[] args) {
for (int i = 0; i < 150; i++) {
Integer a = i;
Integer b = i;
System.out.println(i + " " + (a == b));
}
}
i取值從0到150,每次循環a與b的數值均相等,輸出a == b。運行結果:
0 true
1 true
2 true
3 true
...
126 true
127 true
128 false
129 false
130 false
從128開始a
和b
就不再相等了。
這個例子還容易看出來涉及到int的自動裝箱和自動拆箱,下面來個不太容易看出來的。
例二
public static void main(String[] args) {
Map<Integer, Integer> mapA = new HashMap<>();
Map<Integer, Integer> mapB = new HashMap<>();
for (int i = 0; i < 150; i++) {
mapA.put(i, i);
mapB.put(i, i);
}
for (int i = 0; i < 150; i++) {
System.out.println(i + " " + (mapA.get(i) == mapB.get(i)));
}
}
i
取值從0
到150
,mapA
和mapB
均存儲(i, i)
數值對,輸出mapA
的值與mapB
的值的比較結果。運行結果
0 true
1 true
2 true
3 true
...
126 true
127 true
128 false
129 false
130 false
...
為什么兩個例子都是從0到127均顯示兩個變量相等,而從128開始不相等?
原因分析
自動裝箱
首先回顧一下自動裝箱。對于下面這行代碼
Integer a = 1;
變量a
為Integer
類型,而1
為int
類型,且Integer
和int
之間并無繼承關系,按照Java的一般處理方法,這行代碼應該報錯。
但因為自動裝箱機制的存在,在為Integer類型的變量賦int類型值時,Java會自動將int類型轉換為Integer類型,即
Integer a = Integer.valueOf(1);
valueOf()
方法返回一個Integer類型值,并將其賦值給變量a。這就是int的自動裝箱。
是同一個對象嗎?
再看最開始的例子:
public static void main(String[] args) {
for (int i = 0; i < 150; i++) {
Integer a = i;
Integer b = i;
System.out.println(i + " " + (a == b));
}
}
每次循環時,Integer a = i
和Integer b = i
都會觸發自動裝箱,而自動裝箱會將int轉換Integer類型值并返回;我們知道Java中兩個new出來的對象因為時不同的實例,無論如何==
都會返回fasle。比如
new Integer(1) == new Integer(1);
就會返回false。
那么例子中Integer a = i
和Integer b = i
自動裝箱產生的變量a
和b
就不應該時同一個對象了,那么==
的結果應該時false。128以上為false容易理解,但為何0到127時返回true了呢?==
返回true的唯一情況是比較的兩個對象為同一個對象,那不妨把例子中a
和b
的內存地址都打印出來看看:
for(int i=0;i<150;i++){
Integer a=i;
Integer b=i;
System.out.println(a+" "+b+" "+System.identityHashCode(a)+" "+System.identityHashCode(b));
}
identityHashCode()
方法可以理解為輸出對應變量的內存地址,輸出為:
0 0 762119098 762119098
1 1 1278349992 1278349992
2 2 1801910956 1801910956
3 3 1468253089 1468253089
...
126 126 1605164995 1605164995
127 127 1318497351 1318497351
128 128 101224864 479240824
129 129 1373088356 636728630
130 130 587071409 1369296745
...
竟然從0到127不同時候自動裝箱得到的是同一個對象!從128開始才是正常情況。
看看源碼
“從0到127不同時候自動裝箱得到的是同一個對象”就只能有一種解釋:自動裝箱并不一定new出新的對象。
既然自動裝箱涉及到的方法是Integer.valueOf(),不妨看看其源代碼:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
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之間的值都是直接從緩存中取出的。看看是怎么實現的:如果int型參數i
在IntegerCache.low
和IntegerCache.high
范圍內,則直接由IntegerCache
返回;否則new一個新的對象返回。似乎IntegerCache.low
就是-128,IntegerCache.high
就是127了。
看看IntegerCache的源碼:
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() {}
}
果然在其static塊中就一次性生成了-128到127直接的Integer類型變量存儲在cache[]中,對于-128到127之間的int類型,返回的都是同一個Integer類型對象。
這下真相大白了,整個工作過程就是:Integer.class在裝載(Java虛擬機啟動)時,其內部類型IntegerCache的static塊即開始執行,實例化并暫存數值在-128到127之間的Integer類型對象。當自動裝箱int型值在-128到127之間時,即直接返回IntegerCache中暫存的Integer類型對象。
為什么Java這么設計?我想是出于效率考慮,因為自動裝箱經常遇到,尤其是小數值的自動裝箱;而如果每次自動裝箱都觸發new,在堆中分配內存,就顯得太慢了;所以不如預先將那些常用的值提前生成好,自動裝箱時直接拿出來返回。哪些值是常用的?就是-128到127了。
解決方法
既然我們的目的是比較數值是否相等,而非判斷是否為同一對象;而自動裝箱又不能保證同一數值的Integer一定是同一對象或一定不是同一對象,那么就不要用==,直接用equals()好了。實際上,Integer重寫了equals()方法,直接比較對象的數值是否相等。
for (int i = 0; i < 150; i++) {
Integer a = i;
Integer b = i;
System.out.println(i + " " + (a.equals(b)));
}
這樣返回值就全都是true了。
備注
不僅int,Java中的另外7中基本類型都可以自動裝箱和自動拆箱,其中也有用到緩存。見下表:
基本類型 | 裝箱類型 | 取值范圍 | 是否緩存 | 緩存范圍 |
---|---|---|---|---|
byte | Byte | -128 ~ 127 | 是 | -128 ~ 127 |
short | Short | -2^15 ~ (2^15 - 1) | 是 | -128 ~ 127 |
int | Integer | -2^31 ~ (2^31 - 1) | 是 | -128 ~ 127 |
long | Long | -2^63 ~ (2^63 - 1) | 是 | -128 ~ 127 |
float | Float | -- | 否 | -- |
double | Double | -- | 否 | -- |
boolean | Boolean | true, false | 是 | true, false |
char | Character | \u0000 ~ \uffff | 是 | \u0000 ~ \u007f |