Java StringBuilder and StringBuffer source analysis _java

Source: Internet
Author: User
Tags inheritance stringbuffer

StringBuilder and StringBuffer are classes of two commonly used operation strings. As we all know, StringBuilder is thread-insecure, and stringbuffer is thread-safe. The former is JDK1.5, and the latter is in JDK1.0. Here's an analysis of their internal implementations.

I. The relationship of inheritance

Public final class StringBuffer
extends Abstractstringbuilder
implements Java.io.Serializable, Charsequence Public

Final Class StringBuilder
extends Abstractstringbuilder
implements Java.io.Serializable, Charsequence

As you can see, the inheritance relationships of two classes are identical. Serializable are flags that can be serialized. The Charsequence interface contains the methods of Charat (), Length (), subsequence (), toString (), and the string class implements this interface. The focus here is on abstract class Abstractstringbuilder, which encapsulates the implementation of most operations of StringBuilder and StringBuffer.

Second, Abstractstringbuilder

1. Variables and Construction methods

Char[] value;
int count;
Abstractstringbuilder () {
}
abstractstringbuilder (int capacity) {
  value = new char[capacity];
}
  

Abstractstringbuilder internally uses a char[] array to hold the string, which can be used to specify the initial capacity method at construction time.

2, expansion

public void ensurecapacity (int minimumcapacity) {
  if (minimumcapacity > 0)
    ensurecapacityinternal ( minimumcapacity);
}
 private void ensurecapacityinternal (int minimumcapacity) {
  //overflow-conscious code
  if (Minimumcapacity- Value.length > 0)
    expandcapacity (minimumcapacity);
}
void expandcapacity (int minimumcapacity) {
  int newcapacity = value.length * 2 + 2;
  if (newcapacity-minimumcapacity < 0)
    newcapacity = minimumcapacity;
  if (Newcapacity < 0) {
    if (minimumcapacity < 0)//overflow
      throw new OutOfMemoryError ();
    newcapacity = Integer.max_value;
  }
  Value = arrays.copyof (value, newcapacity);
}

The method of Dilatancy is finally implemented by Expandcapacity (), in which the capacity is first enlarged to the original capacity plus 2, and if this is still less than the specified capacity, then the new capacity is set to minimumcapacity. Then determine if overflow, if overflow, set the capacity to Integer.max_value. Finally, the value is copied, which is obviously a time-consuming operation.

3, Append () method

Public Abstractstringbuilder append (String str) {
    if (str = null) return
      appendnull ();
    int len = Str.length ();
    Ensurecapacityinternal (count + len);
    Str.getchars (0, Len, value, count);
    Count = Len;
    return this;
  }

Append () is the most common method, and it has many forms of overloading. One of the above is used to append a string. If STR is null, the Appendnull () method is invoked. This method is actually to append the ' n ', ' U ', ' l ', ' l ' these several characters. If it is not NULL, the expansion is first and then the GetChars () method of string is appended to append STR to the end of value. Finally, the object itself is returned, so append () can be called continuously.

Third, StringBuilder

Abstractstringbuilder has implemented most of the required methods, StringBuilder and StringBuffer only need to be invoked. Here's a look at StringBuilder's implementation.

1. Construction Device

Public StringBuilder () {
  super;
}
public StringBuilder (int capacity) {
  super (capacity);
}
Public StringBuilder (String str) {
  super (Str.length () +);
  Append (str);
Public StringBuilder (charsequence seq) {This
  (seq.length () +);
  Append (seq);

As you can see, the default size of the StringBuilder is 16. You can, of course, specify the initial capacity, or assign an initial value to a StringBuilder object in an existing sequence of characters.

2, append () method

Public StringBuilder append (String str) {
  super.append (str);
  return this;
}
Public StringBuilder Append (charsequence s) {
  super.append (s);
  return this;
}

Append () A lot of overloaded methods, here casually enumerated two. Obviously, this is the method in the parent class Abstractstringbuilder that is called directly.

3, ToString ()

 Public String toString () {
  //Create a copy, don ' t share the array return
  new String (value, 0, count);
}

The ToString () method returns a new string object that does not share memory with the original object. In fact, the substring () method in Abstractstringbuilder is the same.

Four, Sringbuffer

Stiringbuffer is similar to StringBuilder, but in order to achieve synchronization, many methods use lsynchronized modification, as in the following method:

public synchronized int Length () {return
    count;
}
Public synchronized StringBuffer append (String str) {
  tostringcache = null;
  Super.append (str);
  return this;
}
Public synchronized void SetLength (int newlength) {
  tostringcache = null;
  Super.setlength (newlength);
}

As you can see, the method does add synchronized to the front.
In addition, there is a variable tostringcache in the above append () and the SetLength () method. This variable is the cache for the most recent ToString () method, and any time the StringBuffer is modified, the variable is assigned null. StringBuffer's ToString is as follows:

Public synchronized String toString () {
  if (Tostringcache = = null) {
    Tostringcache = arrays.copyofrange (value, 0, count);
  }
  return new String (Tostringcache, True);
}

In this method, if Tostringcache is null, it is cached first. The string object that is eventually returned is a bit different, and the constructor also has a parameter true. Find the source of the string look at:

 String (char[] Value, Boolean share) {
  //Assert share: ' unshared not supported ';
  This.value = value;
}

The string object originally constructed by this constructor does not actually copy the strings, but it points to the constructor parameters, which is to save time for copying the elements. This constructor, however, has package access and is generally not callable.

Summarize

    • Both StringBuilder and StringBuffer are variable strings, the former thread is unsafe and the latter thread-safe.
    • Most methods of StringBuilder and StringBuffer invoke the implementation of the parent class Abstractstringbuilder. Its expansion mechanism first is to change the capacity of the original capacity of twice times plus 2. The maximum capacity is integer.max_value, i.e. 0x7fffffff.
    • The default capacity for both StringBuilder and StringBuffer is 16, and it's best to anticipate the size of the string to avoid the time consuming of the expansion.

The above is the entire content of this article, I hope that you learn Java in two commonly used operation strings of the class StringBuilder and StringBuffer help.

Related Article

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.