Java: Integer equals vs. ==

As of Java 1.5, you can pretty much interchange Integer with int in many situations.php

However, I found a potential defect in my code that surprised me a bit.java

The following code:git

Integer cdiCt = ...;Integer cdsCt = ...;...if (cdiCt != null && cdsCt != null && cdiCt != cdsCt)
    mismatch = true;

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.express

Changing the conditional to:app

if (cdiCt != null && cdsCt != null && !cdiCt.equals(cdsCt))

fixed the problem.jvm

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.ui

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.this

Is it still not legitimate to use == to compare two Integer values?spa

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:code

Why can't the compiler/JVM just make autoboxing 「just work」?

The JVM is caching Integer values. == only works for numbers between -128 and 127http://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

相關文章
相關標籤/搜索