當你做==
你正在比較相等的參考。這意味着你在說「兩個對象的內存地址是相同的嗎?」
當你做.equals()
你正在比較對象本身的平等。這意味着你說「這兩個對象認爲自己是平等的嗎?」
給出的例子很差。 對於這些由JLS強制執行的數字所做的唯一緩存是.valueOf()
方法。構造函數沒有被緩存。
此外,JLS僅指定您必須緩存的最小 [-128:127]。 JVM實現可能會緩存更多,如果他們選擇的話。這意味着Integer.valueOf(500) == Integer.valueOf(500)
可能在某些機器上爲false
,但在其他機器上爲true
。
class biziclop {
public static void main(String[] args) {
System.out.println(new Integer(5) == new Integer(5));
System.out.println(new Integer(500) == new Integer(500));
System.out.println(Integer.valueOf(5) == Integer.valueOf(5));
System.out.println(Integer.valueOf(500) == Integer.valueOf(500));
}
}
結果:(!評論是寶石)
C:\Documents and Settings\glow\My Documents>java biziclop
false
false
true
false
C:\Documents and Settings\glow\My Documents>
看到更詳細的答案在這裏:Why do people still use primitive types in Java?
那麼,你的筆記是完全錯誤的。 '新的整數(0)==新的整數(0)'將永遠不會,永遠,*永遠***爲真,也不會'新的整數(666)==新的整數(666)'。我建議你請教授澄清他的意思,因爲如果他在考試中期望這一點,他對Java就知之甚少。 – 2011-04-18 13:32:39