問題描述
從 Java 1.5 開始,您幾乎可以在許多情況下將 Integer
與 int
互換.
As of Java 1.5, you can pretty much interchange Integer
with int
in many situations.
但是,我發(fā)現(xiàn)我的代碼中有一個潛在的缺陷,這讓我有點吃驚.
However, I found a potential defect in my code that surprised me a bit.
以下代碼:
Integer cdiCt = ...;
Integer cdsCt = ...;
...
if (cdiCt != null && cdsCt != null && cdiCt != cdsCt)
mismatch = true;
當值相等時,似乎錯誤地設置了不匹配,盡管我無法確定在什么情況下.我在 Eclipse 中設置了一個斷點,發(fā)現(xiàn) Integer
的值都是 137,我檢查了布爾表達式,它說它是假的,但是當我越過它時,它將不匹配設置為真.
appeared to be incorrectly setting mismatch when the values were equal, although I can't determine under what circumstances. I set a breakpoint in Eclipse and saw that the Integer
values were both 137, and I inspected the boolean expression and it said it was false, but when I stepped over it, it was setting mismatch to true.
將條件更改為:
if (cdiCt != null && cdsCt != null && !cdiCt.equals(cdsCt))
解決了問題.
誰能解釋一下為什么會這樣?到目前為止,我只在我自己的 PC 上的本地主機上看到了這種行為.在這種特殊情況下,代碼成功通過了大約 20 次比較,但在 2 次比較失敗.問題始終可以重現(xiàn).
Can anyone shed some light on why this happened? So far, I have only seen the behavior on my localhost on my own PC. In this particular case, the code successfully made it past about 20 comparisons, but failed on 2. The problem was consistently reproducible.
如果這是一個普遍存在的問題,它應該會導致我們的其他環(huán)境(開發(fā)和測試)出現(xiàn)錯誤,但到目前為止,在執(zhí)行此代碼片段的數(shù)百次測試之后,沒有人報告此問題.
If it is a prevalent problem, it should be causing errors on our other environments (dev and test), but so far, no one has reported the problem after hundreds of tests executing this code snippet.
使用 ==
比較兩個 Integer
值仍然不合法嗎?
Is it still not legitimate to use ==
to compare two Integer
values?
除了下面所有的好答案之外,下面的 stackoverflow 鏈接還有很多額外的信息.它實際上會回答我原來的問題,但是因為我沒有在我的問題中提到自動裝箱,所以它沒有出現(xiàn)在選定的建議中:
In addition to all the fine answers below, the following stackoverflow link has quite a bit of additional information. It actually would have answered my original question, but because I didn't mention autoboxing in my question, it didn't show up in the selected suggestions:
為什么編譯器/JVM就不能讓自動裝箱正常工作"?
推薦答案
JVM 正在緩存整數(shù)值.因此,與 ==
的比較僅適用于 -128 到 127 之間的數(shù)字.
The JVM is caching Integer values. Hence the comparison with ==
only works for numbers between -128 and 127.
參考:#Immutable_Objects_.2F_Wrapper_Class_Caching
這篇關于Java:整數(shù)等于 vs. ==的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!