Writing high-quality code: 151 suggestions for improving Java programs (Chapter 1: String ___ suggestion 52 ~ 55), java151
Recommendation 52: String direct value assignment is recommended.
Generally, objects are generated using the new keyword, But there is a second method to generate the String, that is, the direct declaration method that we often use. This method is strongly recommended, however, it is not recommended to assign values using the new String ("A") method. Why? We can see the following code:
Public class Client58 {public static void main (String [] args) {String str1 = "James"; String str2 = "James"; String str3 = new String ("James "); string str4 = str3.intern (); // whether the two direct quantities are equal to System. out. println (str1 = str2); // whether the direct quantity is equal to the object System. out. println (str1 = str3); // whether the objects processed by intern are equal to the direct quantity? System. out. println (str1 = str4 );}}
Check the above program. We use "=" to determine whether the reference addresses of the two objects are the same, that is, whether the object is the same. The printed results are true and false, true. There are two objects with the same direct volume (the String and direct volume after intern processing are the same object), but the objects generated directly through new are not the same. Why?
The reason is that, in order to avoid a large number of String objects in a system (why is a large number of objects generated, because the String is the most frequently used type in the Program ), therefore, a String pool (also called the String Constant Pool, String Pool, String Constant pool, or String Literal Pool) is designed to accommodate String objects in the String Pool, its creation mechanism is as follows: when creating a string, first check whether there is a string with the same nominal value in the pool. If there is a string, it is no longer created. directly return the reference of this object in the pool, if no object exists, it is created, put in the pool, and the reference of the newly created object is returned. This pool is very similar to the pool we usually call. In this example, when creating the first "James" string, first check whether the object exists in the string pool. If no, the "James" string is created and put in the pool, when you create a str2 string, because the string already exists in the pool, the reference of this object is directly returned. At this time, str1 and str2 point to the same address, therefore, "=" is used to determine that it is equal.
Why is the use of new String ("James") not equal? Because directly declaring a String object does not check the String pool, and the object will not be placed in the String pool. Of course, "=" is false.
Why is the intern method equal after processing? Intern checks whether the current object has referenced objects with the same nominal value in the object pool. If yes, it returns the objects in the pool. If not, it is placed in the object pool and returns the current object.
Someone may ask, is it necessary to consider the issue of garbage collection in the pool? You don't have to worry about it. Although every Java object is stored in the heap memory, but the string is very special, it determines its existence in the JVM Constant Pool (Constant Pool) during the compilation period ), garbage collection does not recycle it.
Through the above introduction, we found that Java provides a very good mechanism for creating strings. Using the object pool can not only improve efficiency, but also reduce the memory space usage, we recommend that you use the direct value assignment method during development, unless necessary to create a String object.
Suggestion 53: Pay attention to the parameter requirements passed in the method.
There is a simple requirement to write a method to delete all matching strings from the original string. For example, in "good is good", delete "good ", the Code is as follows:
Public class StringUtils {// Delete the String public static String remove (String source, String sub) {return source. replaceAll (sub ,"");}}
The StringUtils tool class is very simple. It adopts the String replaceAll method, which is used for String replacement. We compile a test case to check whether the remove method is correct, as shown below:
Import static org. junit. assert. *; import org. junit. test; public class TestStringUtils {@ Test public void test () {assertTrue (StringUtils. remove ("good is good", "good "). equals ("yes"); assertTrue (StringUtils. remove ("$ is $", "$ "). equals ("yes "));}}
The first running is the green bar, and the second running is the red bar. Why is the second (assertTrue (StringUtils. remove ("$ is $", "$ "). equals ("yes") does not pass?
The problem lies in the replaceAll method. This method does need to pass two String-type parameters and indeed replaces the strings, but it requires the first parameter to be a regular expression, strings that match the regular expression are replaced. In the above example, the first test case is passed in a string "good", which is a full match search replacement and is handled correctly, in the second test case, a "$" symbol is passed. The "$" symbol indicates the end position of the string in the regular expression, that is, after the replaceAll is executed, an empty string is added at the end of the string, and the result is "$" is "$". Therefore, if the test fails, the test is hard to avoid. If the problem is clear, the solution will come out: replace with the replace method, which is a simplified version of the replaceAll method. Two String parameters can be passed, which is consistent with our encoding intent.
If you read the JDK documentation, you will find that the replace (CharSequence target, CharSequence replacement) method is provided only after version 1.5. Before that, if you want to replace all strings, only the replaceAll method can be used. However, because the second parameter of the replaceAll method uses a regular expression and the parameter type can be CharSequence (the String parent class), it is easy for users to misunderstand, A slight carelessness may lead to serious replacement errors.
Note: The first parameter passed by replaceAll is a regular expression.
54. Suggestion: Use String, StringBuffer, and StringBuilder correctly
The CharSequence interface has three implementation classes related to strings: String, StringBuffer, and StringBuilder. Although they are all related to strings, their processing mechanisms are different.
The String class is an unchangeable volume, that is, it cannot be modified after it is created. For example, a String object such as "abc" is created, it will always be an object with a fixed surface value like "abc" in the memory and cannot be modified, even if you want to try to modify it using the method provided by String, you can either create a new String object or return yourself, for example:
String str = "abc";String str1 = str.substring(1);
Here, str is a string object whose value is "abc". The substring method re-generates a string str1 whose value is "bc ", that is to say, the objects referenced by str will never change once they are generated. Why can I return myself without creating an object? That is because the object is not created when substring (0) is used. JVM returns the reference of str from the string pool, that is, its reference.
StringBuffer is a variable String. Like String, it stores an ordered Character Sequence (an array of char type) in memory. The difference is that the value of the StringBuffer object can be changed, for example:
StringBuffer sb = new StringBuffer("a");sb.append("b");
From the code above, we can see that the sb value is changed. during initialization, it is "a". After the append method, its value is changed to "AB ". Some may ask, what is the difference between this and the String class's connection through "+? For example
String s = "a";s = s + "b";
The difference is that the string variable s is referenced by the "a" object during initialization. After the plus sign is calculated, the variable s is changed to the reference of "AB, however, the initialized "a" object has not changed, but the variable s points to a new reference address. Let's look at the StringBuffer object. Its reference address remains unchanged, but its value changes.
The StringBuffer and StringBuilder are basically the same, both of which are variable character sequences. The difference is that StringBuffer is thread-safe and StringBuilder is thread-insecure, the keyword syschronized exists before the StringBuffer method. This is why the performance of StringBuffer is much lower than that of StringBuffer.
In terms of performance, the operations of the String class are all String objects, while StringBuilder and StringBuffer are only the expansion of a character array. Therefore, the operations of the String class are much slower than those of StringBuffer and StringBuilder.
After figuring out the principles between the three, we can use different character sequences in different scenarios:
Note: select the string type in an appropriate scenario.
Suggestion 55: Pay attention to the position of the string
Take a look at the following program:
public class Client55 { public static void main(String[] args) { String str1 = 1 + 2 + "apples"; String str2 = "apples" + 1 + 2; System.out.println(str1); System.out.println(str2); }}
Check whether the numbers of apples output by the two strings are the same. What if the numbers are the same?
The answer is inconsistent. The value of str1 is "3 apples", and the value of str2 is "apples12". This is a big disparity, but I changed the position of "apples, why is there such a big change?
This is due to java's processing mechanism for the plus sign: In the expression using the plus sign for computation, as long as a String is encountered, all data will be converted to the String type for splicing, if it is raw data, it is directly spliced. If it is an object, the return value of the toString method is called and then spliced, for example:
Str = str + new ArrayList ();
The above is the concatenation of the return value of the toString method of the ArrayList object. Back to the previous question, the Java execution sequence for the str1 string is from left to right, and 1 + 2 is executed first, that is, the arithmetic addition operation, and the result is equal to 3, then concatenate the string and the result is "3 apples". The other form is similar to the following calculation:
String str1 = (1 + 2) + "apples ";
For str2 strings, because the first String type is involved in the computation, the result after adding 1 is "apples 1", which is still a String and then added to 2, the result is still a string, that is, "apples12 ". This indicates that if the first parameter is String, all subsequent calculations will be converted to the String type. Who makes the String the boss!
Note: In the "+" expression, the String has the highest priority.