String StringBuffer StringBuilder

Source: Internet
Author: User

Recently instructed several new students, learning a little string,stringbuffer and StringBuilder class, from the results of feedback, the overall feeling of the depth of learning is not enough to read something. In fact, the JDK source code is more read more interesting. Here is a summary of my reading these source of the Harvest bar.
Note: Although the source code version is JDK6, but personally feel that learning this version of the source code is very helpful to understand the data structure, because string is a struct, it is the encapsulation of Char [], implementation of a lot of char [] operation

The first part: string source code parsing

(1) string implements the Charsequence interface, the method of this interface is not many, the following several:

1234 int length (); Char charAt (int index); Charsequence subsequence (int start, int end);p ublic String toString ();

A deep understanding of the "interface", wait for the time to write it out. I personally feel that the name "interface" is easily misleading, not conducive to interface-oriented programming. Object-oriented programming is a great feat in language design, which realizes the perfect logic of biology, such as the subclass inheriting the parent class, but the concept of the interface is completely subversive to the concept of class and object, discarding the idea of class and object, and pushing the flexibility of thinking to the extreme.
(2) member variable of string

123 Private Final char value[];p rivate final int offset;private final int count;

Final modifies a member variable (property) that must be displayed for initialization. Usually there are two types of initialization, one is initialized at the time of the variable declaration, and the second is to not assign the initial value when declaring the variable, but to assign an initial value to the variable in all the constructors of the class in which it resides. In fact, from the point of view of data structure, string is a struct, it is the encapsulation of Char [], the specific properties include: char [] value, the storage character; offset is the number of chars, and count represents the quantity of char. Value.length and Count are still different, and this is more explicit in the Abstractstringbuilder class.

(3) Relationship with Stringbuffer,stringbuilder:

12345678910 Public String (StringBuffer buffer) {synchronized (buffer) {this.value = arrays.copyof (Buffer.getvalue (), buffer . Length ()); }}public String (StringBuilder builder) {this.value = arrays.copyof (Builder.getvalue (), builder.length ());}

For StringBuffer, it is important to consider the concurrency problem in multi-threaded environments everywhere. Note that the arrays.copyof () method is required. The specific implementation of this method is as follows:

1234567 public static char[] CopyOf (char[] original, int newlength) {char[] copy = new Char[newlength];        System.arraycopy (original, 0, copy, 0, Math.min (original.length, newlength));    return copy; }

The generic overloads of this method are:

1234 public static <T> t[] CopyOf (t[] original, int newlength) {return (t[]) copyOf (original, Newlength, original.getc Lass ());}

and Copyof (original,
Newlength, Original.getclass ()); The specific implementation is as follows:

12345678 9 public static <T,U> t[] CopyOf (u[] original, int newlength, class<? extends t[] > NewType) {        t[] copy = ((object) NewType = = (object) object[].class)             ? (t[]) new object[newlength]            : (T[]) Array.newinstance (Newtype.getcomponenttype (), newlength);         System.arraycopy (original, 0, copy, 0,                          math.min (Original.length, newlength));         return copy;}

Note: For the above generic method, a deep understanding is suggested, where t[] represents the function's return value,<t,u> represents the function's parameter type. Why do you write that? This is a generic scope of knowledge, and this article is no longer in the deep, if you are interested in generic content here, please wait for the next article.
(4) Trim method

12345678910111213141516 Public String trim () {int len = Count;int St = 0;int off = offset;    /* Avoid GetField opcode */char[] val = value; /* Avoid GetField opcode */while ((St < Len) && (Val[off + st] <= ") {st++;} while ((St < Len) && (Val[off + len-1] <= ") {len--;} Return ((St > 0) | | (Len < count)) ? SUBSTRING (ST, Len): this;}

Avoid GetField opcode is based on efficiency considerations, string objects are generated in the heap, so it is better to take offset and value out of the off and Val temporary variables. Similarly, the object chain in JS is the same.
(5) Intern method, you can see the description of the JDK, the explanation is very thorough:
A Pool of strings, initially empty, is maintained privately by the class String.
When the Intern method was invoked, if the pool already contains a string equal to this string object as determined by the Equals (Object) method, then the string from the pool is returned. Otherwise, this string object was added to the pool and a reference to this string object is returned.
It follows that for any of the strings s and T, S.intern () ==t.intern () is true if and only if S.equals (t) is true.
All literal strings and string-valued constant expressions is interned.
The string constant pool, whose initial value is null, is maintained by the class string class on its own.
When the Intern method is called, if the pool already contains a string equal to this string object (whether equality is determined by the Equals (Object) method), the string reference in the pool is returned. Otherwise, this string object is added to the pool, and a reference to this string object is returned. For example: S.intern () ==t.intern () is true for any two strings s and T, when and only if S.equals (t) is true.
All literal strings and string-assignment constant expressions are intern implemented.
"Note" About string constants, a lot of content on the web, a variety of viewpoints have, look a little ridiculous, in fact, look at the JDK notes, all the doubts have disappeared. If you have any questions about this, want to discuss the discussion, please dabigatran again, contact details at the end of this article.
(6) StartsWith method

123456789101112131415161718192021222324252627282930 public boolean startsWith (String prefix) {return startsWith (prefix, 0);} public boolean endsWith (String suffix) {return startsWith (suffix, count-suffix.count);} public boolean StartsWith (Strin g prefix, int toffset) {char ta[] = value;int to = offset + Toffset;char pa[] = prefix.value;int po = prefix.offset;int pc = prefix.count;//Note:toffset might be Near-1>>>1.if ((Toffset < 0) | | (Toffset > COUNT-PC)) {return false;}    while (--pc >= 0) {if (ta[to++]! = pa[po++]) {return false; }}return true;}

This function is very good for self-increment use, and can be referenced. Don't dwell on it here.

Part II: Abstractstringbuilder Source Code Analysis

The relationship between Stringbuffer,stringbuilder is inherited from Abstractstringbuilder, so it is analyzed first.
(1) member variables:

12 Char value[];int count;

Without offset offsets, characters start from the 0-bit position of the value array.
(2) Capacity method:
Returns the Value.length that represents the space that can be stored.
(3) Expansion mode:

1234567891011121314 void expandcapacity (int minimumcapacity) {int newcapacity = (value.length + 1) * 2;        if (Newcapacity < 0) {newcapacity = Integer.max_value; } else if (Minimumcapacity > newcapacity) {newcapacity = minimumcapacity;} Char newvalue[] = new char[newcapacity]; System.arraycopy (value, 0, newvalue, 0, count); value = newvalue; }

(4) Length or truncation

123456789101112131415 public void setLength (int newlength) {if (Newlength < 0) throw new stringindexoutofboundsexception (newlength); if (NE Wlength > Value.length) expandcapacity (newlength), if (Count < Newlength) {for (; count < newlength; count++) Value[count] = ' + ';         } else {count = Newlength; } }

(5) Thin body

123456789 public void TrimToSize () {if (Count < Value.length) {char[] newvalue = new Char[count];             System.arraycopy (value, 0, newvalue, 0, Count);         This.value = newvalue; } }

The methods to be aware of are:
public static native void Arraycopy (object src, int srcpos, object dest, int destpos, int length); very common method.

String StringBuffer StringBuilder

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.