...
Numeric boxed types (for example, Byte
, Character
, Short
, Integer
, Long
, Float
, and Double
) should also be compared using Object.equals()
and not the ==
operator. While reference equality may appear to work for Integer
values between the range -128 and 127, it may fail if either of the operands in the comparison are outside that range. Numeric relational operators other than equality (such as <
, <=
, >
, and >=
) can be safely used to compare boxed primitive types (see EXP03-J. Do not use the equality operators when comparing values of boxed primitives for more information).
Noncompliant Code Example
This noncompliant code example declares two distinct String
objects that contain the same value:
...
The reference equality operator ==
evaluates to true
only when the values it compares refer to the same underlying object. The references in this example are unequal because they refer to distinct objects.
Compliant Solution (Object.equals()
)
This compliant solution uses the Object.equals()
method when comparing string values:
Code Block | ||
---|---|---|
| ||
public class StringComparison { public static void main(String[] args) { String str1 = new String("one"); String str2 = new String("one"); System.out.println(str1.equals( str2)); // Prints "true" } } |
Compliant Solution (String.intern()
)
Reference equality behaves like abstract object equality when it is used to compare two strings that are results of the String.intern()
method. This compliant solution uses String.intern()
and can perform fast string comparisons when only one copy of the string one
is required in memory.
...
When canonicalization of objects is required, it may be wiser to use a custom canonicalizer built on top of ConcurrentHashMap
; see Joshua Bloch's Effective Java, second edition, Item 69 [Bloch 2008], for details.
Applicability
Using reference equality to compare objects can lead to unexpected results.
...
Use reference equality to determine whether two references point to the same object.
Bibliography
[Bloch 2008] | Item 69, "Prefer Concurrency Utilities to wait and notify " |
ES, "Comparison of String Objects Using | |
[JLS 2011] | §3.10.5, "String Literals" |
...