StringBuilder basic overview

Basic concepts:

StringBuilder is also called variable character sequence, it is a string buffer similar to String . That is, it is a container , and many strings can be contained in the container. And be able to perform various operations on the strings in it.

It has an internal array to store the content of the string. When the string is spliced, new content is directly added to the array. StringBuilder will automatically maintain the expansion of the array. The principle is shown in the figure below: (default 16 character space, more than automatic expansion)
Insert picture description here

Construction method:

  • public StringBuilder(): Construct an empty StringBuilder container.
  • public StringBuilder(String str): Construct a StringBuilder container and add strings to it.
public class StringBuilderDemo {
    
    
    public static void main(String[] args) {
    
    
    	//无参构造
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1); 
        //有参构造
        StringBuilder sb2 = new StringBuilder("String");
        System.out.println(sb2); 
    }
}

Common methods:

  • public StringBuilder append(...): Add the string form of any type of data and return the current object itself.
  • public String toString(): Convert the current StringBuilder object to String object.

append method:

The append method has a variety of overloaded forms and can receive any type of parameters. Any data as a parameter will add the corresponding string content to the StringBuilder. E.g:

public class StringBuilderDemo2 {
    
    
	public static void main(String[] args) {
    
    
		//创建对象
		StringBuilder builder = new StringBuilder();
		//public StringBuilder append(任意类型)
		StringBuilder builder2 = builder.append("hello");
		//对比一下
		System.out.println("builder:"+builder);//builder:hello
		System.out.println("builder2:"+builder2);//builder2:hello
		System.out.println(builder == builder2); //true
	    // 可以添加 任何类型
		builder.append("hello");
		builder.append("world");
		builder.append(true);
		builder.append(100);
		//链式编程
		builder.append("hello").append("world").append(true).append(100);
		System.out.println("builder:"+builder);
		//builder:hellohelloworldtrue100helloworldtrue100
	}
}

toString method:

Through the toString method, the StringBuilder object will be converted into an immutable String object. Such as:

public class StringBuilderDemo3 {
    
    
    public static void main(String[] args) {
    
    
        // 链式创建
        StringBuilder sb = new StringBuilder("Hello").append("World").append("Java");
        // 调用方法
        String str = sb.toString();
        System.out.println(str); // HelloWorldJava
    }
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/107514522