In Item-5 of Effctive Java, Mr Bloch expresses that avoid creating unnecessary object. In essence, this requires knowing your tool, Java.
String s = new String("test"); //DON'T DO THIS
The statement creates a new String instance each time it is executed. The improved version is simply the following:
String s = "test";
This version uses a single String instance, rathe rthan creating new one each time it is executed. This idiom is called String Interning.
Here is a really interesting sample code demonstrating String interning.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StringIntern { | |
public static void main(String[] args) { | |
String s1 = "test"; | |
String s2 = "test"; | |
checkEquality(s1, s2); | |
String s3 = new String("test"); | |
String s4 = new String("test"); | |
checkEquality(s3, s4); | |
} | |
public static void checkEquality(String s1, String s2) { | |
System.out.println(System.identityHashCode(s1)); | |
System.out.println(System.identityHashCode(s2)); | |
System.out.println(s1.equals(s2)); | |
System.out.println(s1 == s2); | |
} | |
} |
First checkEquality results that both two strings are exatly same instance with same identity code and both == and equals() give true.
Second checkEquality results that two strings are different instances created with different identity codes and == results false but equals() results true.
396857438
396857438
true
true
2046236531
1294253459
true
false
Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String)
Boolean.TRUE is implemented inside Boolean class as a static final Boolean element:
public static final Boolean TRUE = new Boolean(true);
No comments:
Post a Comment