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.
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