問題描述
可能重復(fù):
整數(shù)包裝器對(duì)象僅共享相同的實(shí)例在值 127 以內(nèi)?
我從 Khalid Mughal SCJP 復(fù)制了以下程序片段,但我無法
理解輸出.
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
}
}
上面的程序?yàn)榈谝粋€(gè)打印語句給出了輸出 true,但它應(yīng)該給出 false,因?yàn)樗桥c == 關(guān)系運(yùn)算符的引用比較.但是第三次??打印給出了錯(cuò)誤,我不明白這種不一致.
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.
非常感謝您的解釋!
推薦答案
在第一種情況下,對(duì)象 i
和 j
都指向同一個(gè)緩存對(duì)象.默認(rèn)情況下,-128 到 127 之間的范圍被緩存為 Integer
對(duì)象.我們可以使用 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
這篇關(guān)于為什么 == 對(duì)于某些 Integer 對(duì)象為真?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!