1. == and String.equals()Firstly look into this code:
String s1 = "test";String s2 = "test";boolean result = s1== s2;What the result will be? It will be true. not because the content of s1 and s2 are equal, but because the s1 and s2 references are so.
The == operator, when applied to references, simply compares the references themselves for equality, and not the referenced objects. s1 s2 here are two references to this "test" string-valued constant in Constant Pool, and we should know all strings in this pool are guaranteed to be unique.
Conversely, if two references are equal using ==, then you can be sure that they refer to identical objects. So if you are comparing strings, and there is a good chance of encountering identical ones, then you can say:
if (s1 == s2 || s1.equals(s2)) ... "Always perform a cheap test before an expensive on, if you possibly can", here == is much cheaper than equals().
2. Interning StringsThe Java String class has a method called intern(), it returns a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Saying:
str = str.intern();
adds the string to the pool if not already there, and returns a reference to the interned string. Interned strings can be compared with each other using ==, which is much cheaper than using equals() to do the comparison. For any two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s.equals(t) is true.
An example of interning strings:
// interning strings
public class str_intern { public static void main(String args[]) { String str = new String("testing"); // interning not done
if (str == "testing")
System.out.println("equal"); else
System.out.println("unequal"); // interning done
str = str.intern();
if (str == "testing")
System.out.println("equal"); else
System.out.println("unequal"); }
}
In the first example, the test str == "testing" compares false, because str is a reference to a string that is a copy of the literal "testing", while "testing" itself is an interned string, and therefore the corresponding references are distinct. In the second example, the test compares true, because str has been interned, and the reference returned from the intern() call is identical to the reference to the "testing" literal already in the internal string pool.
String interning is a very fast way of doing comparisons within a pool of strings, with an initial cost incurred in actually doing the interning, comparing with existed strings by equals(Object).
Trackback: http://tb.donews.net/TrackBack.aspx?PostId=1094772