問題描述
可能重復:
整數包裝器對象僅共享相同的實例在值 127 以內?
我從 Khalid Mughal SCJP 復制了以下程序片段,但我無法
理解輸出.
I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.
public class RQ200_60 {
public static void main(String[] args) {
Integer i = -10;
Integer j = -10;
System.out.print(i==j); // output: true -- why true?
System.out.print(i.equals(j)); // output: true
Integer n = 128;
Integer m = 128;
System.out.print(n==m); // output: false
System.out.print(n.equals(m)); // output: true
}
}
上面的程序為第一個打印語句給出了輸出 true,但它應該給出 false,因為它是與 == 關系運算符的引用比較.但是第三次??打印給出了錯誤,我不明白這種不一致.
The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.
非常感謝您的解釋!
推薦答案
在第一種情況下,對象 i
和 j
都指向同一個緩存對象.默認情況下,-128 到 127 之間的范圍被緩存為 Integer
對象.我們可以使用 JVM arguments
In the first case, both the objects i
and j
are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer
Object. We can increase the range using JVM arguments
這篇關于為什么 == 對于某些 Integer 對象為真?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!