As of Java 1.5, you can pretty much interchange with in Integer
int
many situations.
However, I found a potential defect in my code that surprised me a bit.
The following code:
Integer cdict = ...; integer CDSCT = ...; ... if (cdict! = NULL && CDSCT! = NULL && cdict! = CDSCT) mismatch = true;
Appeared to is incorrectly setting mismatch when the values were equal, although I can ' t determine under what circumstance S. I set a breakpoint in Eclipse and saw that the Integer
values were both 137, and I inspected the Boolean expression and I T said it is false, but when I stepped over it, it is setting mismatch to true.
Changing the conditional to:
if (cdict! = NULL && CDSCT! = null &&!cdict.equals (CDSCT))
Fixed the problem.
can anyone shed some light on what this happened? So far, I had only seen the behavior in my localhost on my own PC. In this particular case, the code successfully made it past about comparisons, but failed on 2. The problem was consistently reproducible.
If It is a prevalent problem, it should being causing errors on our other environments (Dev and test) Reported the problem after hundreds of tests executing this code snippet.
Is it still not legitimate to use to ==
compare the Integer
values?
In addition to all the fine answers below, the following-StackOverflow link has quite a bit of additional information. It actually would has answered my original question, but because I didn ' t mention autoboxing in my question, it didn ' t sh ow up in the selected suggestions:
Why can ' t the COMPILER/JVM just do autoboxing "just work"?
The JVM is caching Integer values. = = only works for numbers between-128 and 127Http://www.owasp.org/index.php/J Ava_gotchas#immutable_objects_.2f_wrapper_class_caching
Java:integer equals vs. = =