...
As a general rule, use the Object.equals()
method to check whether two objects are abstractly equal to each other . Programs must reserve use of and the equality operators ==
and !=
for testing to test whether two references specifically refer to the same object; this is reference . This latter test is referred to as referential equality. Also see MET09-J. Classes that define an equals() method must also define a hashCode() method .
...
The reference equality operator ==
evaluates to true
only when the values it compares reference the same underlying object. This noncompliant example declares two distinct String
objects that contain the same value to be true
. The references, however, are unequal because they reference distinct objects.
Code Block | ||
---|---|---|
| ||
public class StringComparison { public static void main(String[] args) { String str1 = new String("one"); String str2 = new String("one"); System.out.println(isEqual( str1, str2)); // prints "false" } public static boolean isEqual(String str1, String str2) { boolean result; // test for null is redundant in this case, but required for full generality if (str1 == null) { result = str2 == null; } else { result = str1 == str2; } return result; // false! } } |
Compliant Solution (Object.equals()
)
...
Code Block | ||
---|---|---|
| ||
public class StringComparison { public static booleanvoid isEqual(main(String[] args) { String str1, = new String str2) { boolean result; // test for null is redundant in this case, but required for full generality("one"); String str2 = new String("one"); System.out.println(isEqual(str1, str2)); // prints "true" } public static boolean isEqual(String str1, String str2) { boolean result; if (str1 == null) { result = (str2 == null); } else { result = str1.equals(str2); } return result; // true } } |
Compliant Solution (String.intern()
)
...
ES: Comparison of String objects using == or != | |
[JLS 2005] | |
|
02. Expressions (EXP) EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays