Reprint-Write high-quality code: 151 Suggestions for improving Java programs (4th: string ___ recommended 52~55)

Source: Internet
Author: User
Tags ord

Read Catalogue

    • Recommendation 52: Recommended use of String direct value assignment
    • Recommendation 53: Note The parameter requirements passed in the method
    • Recommendation 54: Use String, StringBuffer, StringBuilder correctly
    • Recommendation 55: Note the location of the string
Back to top tip 52: Recommended use of String direct value assignment

Generic objects are generated from the new keyword, but there is a second way to generate the String, which is the direct declaration that we often use, which is highly recommended, but it is not recommended to use the new string ("A") to assign a value. Why is it? Let's look at 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 ();        Two direct quantities are equal        System.out.println (str1 = = str2);        The direct volume and the object are equal        System.out.println (str1 = = STR3);        Whether the object after intern processing is equal to the direct amount        System.out.println (str1 = = STR4);}    }

Note The above program, we use "= =" to determine whether the reference address of two objects is the same, that is, to determine whether the same object, the result of printing is true,false,true. That is, there are two direct quantities of the same object (the string and the direct amount after the intern processing are the same object), but the objects generated directly from new are not equal, why?

The reason is that Java, in order to avoid a large number of string objects in a system (why it is produced in large numbers, because the string string is the most commonly used in the program), so the design of a string pool (also known as a string of constant pool, strings pool or string Constant pool or string Literal pool), where a string string object is accommodated in a pool of strings, it is created in such a way that, when a string is created, the pool is first checked for strings with equal literal values, and if so, no longer created. Directly returns a reference to the object in the pool, if none is created, then placed in the pool, and returns a reference to the new object, which is very close to what we normally call a pool. For this example, when you create the first "James" string, check that there is no object in the string pool, find it, and then create the string "James" and put it in the pool, when the STR2 string is created, because the string is already in the pool, the reference to the object is returned directly, STR1 and str2 point to the same address, so use "= =" to determine that it is of course equal.

Why is it not equal to use the new String ("James")? Because declaring a string object directly does not check the pool of strings, nor does it put the object into a string pool, which of course "= =" is False.

Then why is the intern method treated equal again? Because intern checks whether the current object has the same literal reference object in the object pool, returns the object in the pool if one exists, and if not, places it in the object pool and returns the current object.

Some people may ask, put in the pool, is not to consider the garbage collection problem ah? Not to worry, although every object in Java is stored in heap memory but the string is very special, it has been determined at compile time that it exists the JVM's Chang (Constant Pool), garbage collection does not recycle it.

From the above introduction, we found that Java in the creation of the string does provide a very good mechanism, the use of object pooling can not only improve efficiency, but also reduce the memory footprint, we recommend that you use the direct value in the development of the method, unless necessary to establish a string object.

Back to top tip 53: Note The parameter requirements passed in the method

There is a simple need to write a method that removes all strings that match it from the original string, such as "OK" in the "Good good", the code is as follows:

public class StringUtils {    //delete string public    static string remove (string source, String sub) {        return source.rep Laceall (Sub, "");}    }

StringUtils Tool class is simple, it takes the ReplaceAll method of string, the method is to do string substitution, we write a test case, check the Remove method is correct, as follows:

Import static Org.junit.assert.*;import Org.junit.test;public class Teststringutils {    @Test public    void Test () {Asserttrue (Stringutils.remove ("Good Good        ", "good"). Equals ("yes"));        Asserttrue (Stringutils.remove ("$ is $", "$"). Equals ("yes"));}    }

Run alone the first is the green bar, run separately the second is the red bar, why the second one (Asserttrue ("yes" , "$"). Equals ("yes")) does not pass?

The problem is that on the ReplaceAll method, the method does need to pass two arguments of type string and indeed string substitution, but it requires the first argument to be a regular expression, and the string that conforms to the regular expression is replaced. For the above example, the first test case passed in is a string "good", which is a full match lookup replacement, handled very correctly, the second Test case passed in a " " symbol number " " & #x662F; " " > " is "

If you look at the JDK documentation, you will find that the replace (charsequence target,charsequence Replacement) method is only available after the 1.5 release, before this, if you want to swap a string for all, You can only use the ReplaceAll method, but because the second parameter of the ReplaceAll method uses a regular expression, and the parameter type can be (the parent class of string) as long as it is charsequence, it is easy for the user to misunderstand, A slight carelessness can lead to a serious replacement error.

 Note: The first argument passed by ReplaceAll is a regular expression

Back to top recommendation 54: Correct use of string, StringBuffer, StringBuilder

The Charsequence interface has three implementation classes related to strings, string, StringBuffer, and StringBuilder, although they are all related to strings, but their processing mechanisms are different.

The string class is an immutable amount that cannot be modified after creation, such as creating a string object such as "ABC", which in memory will always be an object with fixed surface values such as "ABC" and cannot be modified, even if you want to try to modify it with the method provided by string. It is either to create a new string object or to return to itself, for example:

String  str = "ABC"; String str1 = str.substring (1);

Where Str is a string object whose value is "abc", and a string str1 is regenerated by the substring method, whose value is "BC", which means that the object referenced by STR will never change. Why is it that it is possible to return without creating an object? That's because using substring (0) does not create objects. The JVM returns a reference to str from the string pool, that is, its own reference.

StringBuffer is a mutable string that, like string, holds an ordered sequence of characters in memory (an array of type char), and the difference is that the value of the StringBuffer object is modifiable, for example:

StringBuffer sb = new StringBuffer ("a"); Sb.append ("B");

From the above code, we can see that the value of SB is changed, the initialization time is "a", after the Append method, its value becomes "AB". One might ask, what is the difference between a string class and a "+" connection? For example

String s = "a"; s = s + "B";

There is a difference, the string variable s initialization is a "a" object reference, after the plus sign calculation, the s variable is modified to "AB" reference, but the initialized "a" object has not changed, but the variable s point to the new reference address, and then look at the StringBuffer object, its reference address is unchanged, But the value is changing.

StringBuffer and StringBuilder are basically the same, are variable character sequences, the difference is: StringBuffer is thread-safe, StringBuilder is thread insecure, turn over the source code of both, You will find that there are keyword syschronized before the StringBuffer method, which is why StringBuffer is far below StringBuffer in performance.

In terms of performance, because the operation of the string class is the object that produces a string, and StringBuilder and StringBuffer are only a single character array, the operation of the string class is much slower than the StringBuffer and StringBuilder.

Figuring out the principle of the three, we can use different sequences of characters in different scenarios:

    1. Use the scenario of the String class: String classes can be used in scenes where the strings do not change frequently, such as declarations of constants, small amounts of variable operations, and so on;
    2. Using the StringBuffer scenario: with frequent string operations (such as stitching, replacing, deleting, etc.) and running in multithreaded environments, you might consider using StringBuffer, such as XML parsing, HTTP parameter parsing, and encapsulation.
    3. Using the StringBuilder scenario: with frequent string operations (such as stitching, replacing, deleting, etc.) and running in a single-threaded environment, consider using StringBuilder, such as the concatenation of SQL statements, JSON encapsulation, and so on.

  Note: Select the string type in the appropriate scenario

Back to top tip 55: Note the location of the string

Look at the following procedure:

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);    }}

Think about whether the number of apples in the output of the two strings is the same, and if so, how many?

The answer is inconsistent, the value of str1 is "3apples", the value of str2 is "APPLES12", which is very large, but the "apples" changed position, why such a big change?

It all stems from Java's handling of the plus sign: in expressions that are evaluated with a plus sign, all data is converted to a string type for concatenation if it encounters a string string, and if it is the original data, it is directly spliced, as an object, The return value of the ToString method is called and then spliced, such as:

str = str + new ArrayList ();

Above is the call to the ArrayList object's ToString method return value for stitching. Back to the previous question, on the str1 string, Java execution order is from left to right, first execute 1+2, that is, arithmetic addition operation, the result is equal to 3, and then concatenation with the string, the result is "3 apples", the other form similar to the following calculation:

String str1 = (1 + 2) + "apples";

For STR2 strings, since the first one involved is a string type, the result of adding 1 is "apples 1", which is still a string and then added to 2, and the result is a string, also known as "APPLES12". This means that if the first argument is a string, all subsequent computations will be converted to string type, who makes the string the eldest!

 Note: in the "+" expression, the string string has the highest precedence.

Reprint-Write high-quality code: 151 Suggestions for improving Java programs (4th: string ___ recommended 52~55)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.