Integer Equality in Java: Unraveling the == vs. equals Quandary
Java's introduction of autoboxing in version 1.5 allowed for convenient interchanging of primitive types like int and their corresponding wrapper classes such as Integer. However, a recent observation has raised questions about the validity of using == for comparison of Integer values.
Consider the following code:
Integer cdiCt = ...; Integer cdsCt = ...; ... if (cdiCt != null & cdiCt != cdsCt) mismatch = true;
Surprisingly, this code would sometimes set mismatch to true even when the values of cdiCt and cdsCt were equal. Using a breakpoint in Eclipse revealed that both Integer values were equal to 137, yet the conditional expression evaluated to false.
Changing the conditional to use equals() instead:
if (cdiCt != null & cdiCt != null & !cdiCt.equals(cdsCt))
resolved the issue. This raises the question: is it still not advisable to use == for comparing two Integer values?
The answer lies in the Java Virtual Machine (JVM) caching of Integer values. To improve performance, the JVM caches Integer values between -128 and 127. This means that when you compare two Integer values within this range using ==, they will only be equal if they refer to the same cached instance.
However, if the values fall outside this range or are not autoboxed, they will be treated as distinct objects. This can lead to unexpected behavior, as demonstrated in the provided example.
Therefore, it is generally not recommended to rely on == for comparing Integer values, especially when they may exceed the cached range or if precision is critical. Instead, using equals() is the safer approach to ensure reliable equality comparisons.
The above is the detailed content of Java Integer Comparison: When Should You Use == vs. equals()?. For more information, please follow other related articles on the PHP Chinese website!