Java Common Classes

Source: Internet
Author: User

StringBuffer and StringBuilder

What is it? string buffers

Working principle:

Pre-Request a piece of space in memory to accommodate the sequence of characters, and automatically expand to accommodate more character sequences if the reserved space is not sufficient

The difference between StringBuffer, StringBuilder, and string:

String is an immutable sequence of characters that stores strings in a constant pool

StringBuffer the bottom layer is a char array, but the array is mutable and can be automatically enlarged

 Public Final classStringBufferextendsAbstractstringbuilderImplementsjava.io.Serializable, charsequence{/*** A Cache of the last value returned by toString.     Cleared * Whenever the StringBuffer is modified. */    Private transient Char[] tostringcache; /*** Constructs a string buffer with no characters in it and an * initial capacity of characters. */     PublicStringBuffer () {Super(16);//The default capacity is    }     PublicStringBuffer (intcapacity) {        Super(capacity); }       PublicStringBuffer (String str) {Super(Str.length () + 16);    Append (str); }}

The default capacity of StringBuilder and StringBuffer is 16

Abstract class Implements appendable, charsequence {    /**     * The value is used for character storage.      */    Char [] value;     /** }

Inside is a char array, then the array is fixed, the length will not change, then the automatic expansion is what? is to build a new array, copy the original array data, so it is more time consuming memory,

It is best to predict the required capacity when creating objects of these two classes, create objects in a specified capacity, and improve efficiency by reducing the copying of arrays.

Java Common Classes

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.