問題描述
class D {
public static void main(String args[]) {
Integer b2=128;
Integer b3=128;
System.out.println(b2==b3);
}
}
輸出:
false
<小時>
class D {
public static void main(String args[]) {
Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);
}
}
輸出:
true
注意:-128 到 127 之間的數字為真.
Note: Numbers between -128 and 127 are true.
推薦答案
當您在 Java 中編譯數字文字并將其分配給整數(大寫 I
)時,編譯器會發出:
When you compile a number literal in Java and assign it to a Integer (capital I
) the compiler emits:
Integer b2 =Integer.valueOf(127)
這行代碼也是在你使用自動裝箱的時候生成的.
This line of code is also generated when you use autoboxing.
valueOf
的實現使得某些數字被池化",它為小于 128 的值返回相同的實例.
valueOf
is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.
來自 java 1.6 源代碼,第 621 行:
From the java 1.6 source code, line 621:
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
high
的值可以通過系統屬性配置為另一個值.
The value of high
can be configured to another value, with the system property.
-Djava.lang.Integer.IntegerCache.high=999
-Djava.lang.Integer.IntegerCache.high=999
如果您使用該系統屬性運行程序,它將輸出 true!
If you run your program with that system property, it will output true!
顯而易見的結論:永遠不要依賴兩個引用是相同的,總是用 .equals()
方法比較它們.
The obvious conclusion: never rely on two references being identical, always compare them with .equals()
method.
所以 b2.equals(b3)
將為 b2,b3 的所有邏輯相等值打印 true.
So b2.equals(b3)
will print true for all logically equal values of b2,b3.
請注意,Integer
緩存不是出于性能原因,而是為了符合 JLS,第 5.1.7 節;必須為值 -128 到 127(含)提供對象標識.
Note that Integer
cache is not there for performance reasons, but rather to conform to the JLS, section 5.1.7; object identity must be given for values -128 to 127 inclusive.
Integer#valueOf(int) 也記錄了這種行為:
通過緩存頻繁請求的值,此方法可能會顯著提高空間和時間性能.此方法將始終緩存 -128 到 127(含)范圍內的值,并可能緩存此范圍之外的其他值.
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.
這篇關于為什么在比較 Java 中的整數包裝器時 128==128 為假但 127==127 為真?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!