Brief analysis of Stringbuff append source code in Java

Source: Internet
Author: User

Public synchronized StringBuffer append (String str) {
Super.append (str);
return this;
}//Synchronization method

  public abstractstringbuilder Append (String str) {
        if ( str = = null) str = "NULL";
        int len = Str.length ();
        ensurecapacityinternal (count + len); //whether to enlarge the array, if the expansion, Returns the array in which the original data was copied into
        str.getchars (0, Len, value, count);      //Copy str into array
        count + = len;
        return this;
   }

private void ensurecapacityinternal (int minimumcapacity) {
Overflow-conscious Code
if (Minimumcapacity-value.length > 0)//The length of the data in the original array + the length of the new string to be copied exceeds the length of the original array.
Expandcapacity (minimumcapacity);
}

void expandcapacity (int minimumcapacity) {
int newcapacity = value.length * 2 + 2; Expansion in proportion to 2 * len + 2 of the original array length
if (newcapacity-minimumcapacity < 0)
newcapacity = minimumcapacity; When a string that requires append is very long, it appears
if (Newcapacity < 0) {//Oom
if (minimumcapacity < 0)//Overflow
throw new OutOfMemoryError ();
newcapacity = Integer.max_value;
}
Value = arrays.copyof (value, newcapacity); Copy the original data into an enlarged array to return
}

The reference source code, oneself in the engineering code simple realization function.

byte[] bytes = new BYTE[16]; Stringbuff default initialization of source code is 16 bytes
String str = "Hellowewewehellowewewe"; //
bytes = arrays.copyof (bytes, 100); Simple expansion, omitting the judgment
Str.getbytes (0, str.length (), bytes, 0);

System.out.println (bytes);

for (int i = 0; i <; i++) {
System.out.println (Bytes[i]);
}

Brief analysis of Stringbuff append source code in Java

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.