...
Code Block | ||
---|---|---|
| ||
public class GoodComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
boolean result;
if (str1 == null) {
result = (str2 == null);
} else {
result = str1.equals(str2);
}
System.out.println(result); // prints true
}
}
|
Compliant Solution (String.intern()
)
Reference equality behaves like abstract object equality when comparing two strings that are each the result of the String.intern()
method. When a task requires keeping This solution can be used for fast string comparisons when only one copy of each string in memory, as well as performing quick repeated string comparisons, this compliant solution may be usedis required.
Code Block | ||
---|---|---|
| ||
public class GoodComparison {
public static void main(String[] args) {
String str1 = new String("one");
String str2 = new String("one");
boolean result;
if (str1 != null) {
str1 = str1.intern();
}
if (str2 != null) {
str2 = str2.intern();
}
result = str1 == str2;
System.out.println(result); // prints true
}
}
|
Use this approach with care; performance and clarity could be better served by use of code that applies the Object.equals()
approach and lacks any dependence on reference equality.
...