Commonly used classes (2) StringBuffer and StringBuilder

1 Overview

java.lang.StringBuffer represents a variable character sequence  , you can add, delete, or modify the content of the string, and no new objects will be generated at this time.

StringBuilder represents also a variable character sequence , which can add, delete, and modify the content of the string, and no new objects will be generated at this time.

Screenshot of StringBuffer's source code:

 

Screenshot of StringBuilder's source code:

Compared with the private final byte[] value of the String class  that is, Stringbuffer and StringBuilder are variable character sequences, they both inherit AbstractStringBuffer, and this abstract class has a byte[] value (not final) to store strings. .

First, here is a frequently asked question in interviews:

2. What are the similarities and differences between String, StringBuffer and StringBuilder?

String : immutable character sequence: the bottom layer uses char[] storage

StringBuffer : Variable character sequence: thread is safe, low efficiency, the bottom layer is stored using char[]

StringBuilder : Variable character sequence: thread is also unsafe and efficient, the bottom layer uses char [] to store

3. Source code analysis

Source code analysis of the three :

String str1 = new String(); equivalent to char [] value = new char[0]

String str2 = new String("abc"); Equivalent to char [] value = new char[ ]{'a','b','c'}

StringBuffer sber1 = new StringBuffer(); The bottom layer is to help you create a character array of length 16 by default, char [] value = new char[16]

   

The parameterized construction method of the parent class:

StringBuffer sber2 = new StringBuffer("abc"); The bottom layer is to help you create a created string length + 16 by default, char [] value = new char ["abc".length +16]

The parameterized construction method of the parent class:

1. There will be questions here? ? ? , If we create a string of "abc" StringBuffer, we are outputting its length, will length() be 19 or 3? ?

StringBuffer stringBuffer = new StringBuffer("abc");
System.out.println(stringBuffer.length());

 The answer is 3. The debug mode is used to check the source code. It can be seen that it is using str="abc" and str.length; to modify the value of the count of the AbstractStringbuilder of the parent class to 3.

When looking at the explanation of count, and the length() method: used

Get length is used

2. Another question is that the bottom layer of the array is not enough to accommodate when adding? ? ? Does the array out of bounds? ? ?

In fact, it is the underlying expansion array

When the default size is exceeded, a larger array will be created [ Create (expand the original capacity)*2 + 2 ] When created with no parameters, the original capacity is 16, and the expansion after exceeding it is 34, and the original array content is changed. Copy it over and discard the old array.

The source code goes through the debug process:

StringBuilder and StringBuffer are the same, the method content. It's just that synchronized synchronization is added to the method to solve the thread safety problem.

4. Common methods of StringBuffer

Method prototype Role and meaning
StringBuffer append(xxx) Provides a lot of append() methods for string splicing
StringBuffer delete(int start,int end) Delete the content of the specified subscript position
StringBuffer replace(int start, int end, String str) Replace the position of the (start, end) subscript with str
StringBuffer insert(int offset, xxx) Insert xxx at the specified subscript position
StringBuffer reverse() Reverse the current character sequence
public int indexOf(String str) Returns the index of the first occurrence of the specified substring in this string
public int length() Returns the length of the string
public char charAt(int n ) Returns the character under the index
public void setCharAt(int n ,char ch) Set the ch character to the specified subscript position in the string

When append and insert, if the length of the original value array is not enough, it can be expanded

A simple summary is to add [append ()] delete [delete ()] change [setcharAt (int n)] check [charAt (int n)] insert [insert (int index, xxx)]

5. Comparison of efficiency of String, StringBuffer, StringBuilder

Code demo:

package day02;

import org.junit.Test;
public class StringMain {
    @Test
    public void test01(){
            long startTime = 0L;
            long endTime = 0L;
            String text = "";
            StringBuffer buffer = new StringBuffer("");
            StringBuilder builder = new StringBuilder("");
            //开始对比
            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                buffer.append(String.valueOf(i));
            }
            endTime = System.currentTimeMillis();
            System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                builder.append(String.valueOf(i));
            }
            endTime = System.currentTimeMillis();
            System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
            startTime = System.currentTimeMillis();
            for (int i = 0; i < 20000; i++) {
                text = text + i;
            }
            endTime = System.currentTimeMillis();
            System.out.println("String的执行时间:" + (endTime - startTime));
    }
}

Output:

Execution time of
StringBuffer : 10 Execution time of StringBuilder: 4
Execution time of String: 223

It is clear that String is the slowest, and StringBuffer is the second (it guarantees thread safety, so it is slower than StringBuilder) StringBuilder is the fastest.

High to low efficiency: StringBuilder> StringBuffer> String

Interview questions:

String str = null;
StringBuffer sb = new StringBuffer();
sb.append(str);
System.out.println(sb.length());//
System.out.println(sb);//
StringBuffer sb1 = new StringBuffer(str);
System.out.println(sb1);

What is the output?

4

null

Report an error

Check the source code to know:

 

 

Guess you like

Origin blog.csdn.net/weixin_43725517/article/details/112849130