JAVA source code JDK (3) -- String, StringBuffer, StrinBuilder

Source: Internet
Author: User

In Java, except for the eight basic types, the longest use should be the String class. Let's take a look at how the source code in JDK builds a series of classes including String, StringBuffer, and StrinBuilder. Java. lang. String in JAVA, the String class is a very special class. Let's take a look at how it represents a String. First, let's take a look at several important attributes. The source code is as follows:/** The value is used for character storage. */private final char value [];/** The offset is the first index of the storage that is used. */private final int offset;/** The count is the number of characters in the String. */private final int count; yes. In fact, String is stored in a char array. offset indicates the starting position of char. Count indicates the length of the string. The length () method of the string has only one return count line. The attributes here are all final, which is why the String value cannot be changed [not because of final class String's final yo ]. The advantage of doing so is that String objects can be shared among different users, which is thread-safe. Let's look at a constructor: 1 public String (String original) {2 int size = original. count; 3 char [] originalValue = original. value; 4 char [] v; 5 if (originalValue. length> size) {6 // if the length of the input original storage char [] is greater than the length of the string to be constructed, copy the valid part of original. 7 int off = original. offset; 8 v = Arrays. copyOfRange (originalValue, off, off + size); 9} else {10 // because the length of the input original storage char [] is equal to the length of the string to be constructed, therefore, copy11 v = originalValue; 12} 13 this. offset = 0; 14 this. count = size; 15 this. value = v; 16} I'm not talking about this. I was surprised when I first saw row 2nd. Is the count attribute of the String class private. Later, after self-experiment, I repeatedly recalled the instructor's description of private when I was a beginner in JAVA. The Attribute Modified by private can only be accessed within the class, so I suddenly realized that. Recognizing the private keyword is also a result. This constructor may have translated the JDK comments. Here there are two points. One is the 8th rows of array replication, in which System is used. the arraycopy () method is the fastest way to copy an array in JAVA. [This is a native method. I don't know how to implement it at the underlying layer. I guess it is through the address in the memory ]. The v = originalValue of the second row is used to construct the String and the new String, the value attribute is directed to the same char [] [In fact, this does not matter, because String. value is final ]. The character set constructor is not mentioned here. It is annoying to convert character sets. The following describes the implementation of several common Sring Methods: public boolean equals (Object anObject) View Code first compares hashCode and then traverses and compares the values of two strings. There is nothing to say. Public boolean startsWith (String prefix, int toffset) View Code is also very simple, traversing the value of the String. But the comment is very interesting:-1> 1. [-1's unsigned one-bit right shift, that is, the maximum integer value. You know] public int indexOf (String str) View Code we will have a trap when using this method, that is, sourceString. indexOf (""), the input null string will return 0. Public String substring (int beginIndex, int endIndex) View Code is simple. It constructs a new String. In short, these commonly used methods are nothing more than repeated operations on char. However, when it comes to the String class, we have to mention the String Pool, which is a cache mechanism by JVM to improve efficiency. [As for the JVM principle, the research level is more in-depth, I think I will know about it later ]. It is important to know when the String object will be created in the String Pool, when it will be created in the Heap, and to point the reference to it. When creating a String, the JVM manages the following features: Whenever a String object is created in any way, JVM searches for whether a String object with the same content exists in the String Pool. If not, a String is created in the Pool. When you concatenate a new keyword or a string containing a variable, the object is created in Heap and the reference is directed to the object. [String Pool maintained at the same time] When the equal sign is directly specified or the String is concatenated, only the String Pool is operated. If this String is available, the reference is directed directly, if not, point to after creation. If you are interested, try it by yourself. Here are several examples. Public native String intern (); finally, intern (). This is a native method, and its execution result is to point the String reference to the object in the String Pool. In this way, the objects in Heap can be recycled. Java. lang. StringBuffer we often need to change the String, but the String is immutable, so we have to concatenate A String object to meet the changing needs. If you splice strings frequently, a large number of objects are generated, which consumes a lot of performance. So now it's StringBuffer's turn. As the name suggests, this is a string buffer and can be changed at will. The main operations on StringBuffer are append and insert. Public synchronized StringBuffer append (String str) 1 public synchronized StringBuffer append (String str) {2 super. append (str); // The parent class method is as follows 3 return this; 4} 1 public AbstractStringBuilder append (String str) {2 if (str = null) str = "null "; 3 int len = str. length (); 4 if (len = 0) return this; 5 int newCount = count + len; 6 if (newCount> value. length) 7 expandCapacity (newCount); // The expansion method is as follows: 8 str. g EtChars (0, len, value, count); 9 count = newCount; 10 return this; 11} 1 void expandCapacity (int minimumCapacity) {2 int newCapacity = (value. length + 1) * 2; 3 if (newCapacity <0) {4 newCapacity = Integer. MAX_VALUE; 5} else if (minimumCapacity> newCapacity) {6 newCapacity = minimumCapacity; 7} 8 value = Arrays. copyOf (value, newCapacity); 9} From the above we can see that, if the variable is NULL when splicing a string, it is processed by "null", and the second is the expansion. When constructing a StringBuffer, if we do not set a length, JDK defaults to 16. If the length of the final concatenated string is far beyond this length, stringBuffer is frequently used for resizing. Therefore, it is a good habit to input an estimated length parameter in new StringBuffer. The difference between java. lang. StringBuilder and StringBuffer is synchronized, which improves efficiency. I tested it here, which is about twice the speed. The test Code is as follows: View Code Test Result: The average time consumed by StringBuffer is 399 ms. The average time consumed by StringBuilder is 254 ms. Here is the learning result. Learning is a joy and a sense of accomplishment.

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.