(field == o.field || (field != null && field.equals(o.field)))
Read verbosely translates to
If both are null or they are interned then they are `equal`.
If they are not equal and field is not null,
Then the strings may have equality even if they are not interned.
So do a content check for equality of the strings
Basically what he is saying is, that if string1 == string2
, then ether they are both null
or both are not null
, If both are not null and are equal, then the strings must be interned
. However if string1 != string2
then one of there things but be true.
- field is null or o.field is null
- The strings have different content
- The strings have the same content and they are not interned
The advantage of doing this is you don't always have to do a comparison for equality by length, then character by character. This can be rather slow if both strings are very, very long.
What is String interning?
Code Example:
public class InternedDemo {
public static void main(String[] args) {
String s1 = "hello world";
String s2 = "hello world";
String s3 = new String("hello world");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s2 == s3); // false
System.out.println(s1.equals(s3)); // true
System.out.println(s2.equals(s3)); // true
}
}