String concatenation problem
Since the contents of the object of the String class immutable, so every time string splicing, always creates a new object in memory. E.g:
String str = "Hello";
str += "World";
System.out.println(s);
//HelloWorld
In the API of the String class has this description: the string is constant, their value can not be changed after creation.
According to our analysis of the code words, in fact, it produced a total of three strings, that is "Hello"
, "World"
and "HelloWorld"
. First point reference variable s Hello
new string subject object, splicing out the final point, i.e. HelloWord
.
It can be seen, if the string splicing operation, each stitching, will build a new String object, time consuming and a waste of space. To solve this problem, you can use java.lang.StringBuilder
the class.
StringBuilder Overview
Now java.lang.StringBuilder
the API, StringBuilder also known as a variable sequence of characters, which is similar to a string buffer String, method calls can be changed by some length and content of the sequence.
StringBuilder original string buffer is that it is a container, which may hold a lot of strings. Wherein the string and can perform various operations.
When it has an array of internal string used to store content, a string concatenation, adding new content directly in the array. StringBuilder automatically maintains an array of expansion. Principle as shown below :( default 16 character spaces, more than automatic expansion)
Construction method
According to the API documentation StringBuilder, there are two construction methods used:
public StringBuilder()
: StringBuilder Constructs an empty container.public StringBuilder(String str)
: StringBuilder a container structure, and the string added.
StringBuilder sb1 = new StringBuilder();
System.out.println(sb1); // (空白)
// 使用带参构造
StringBuilder sb2 = new StringBuilder("str");
System.out.println(sb2); // str
Common method
StringBuilder two commonly used methods are:
public StringBuilder append(...)
: Add the string form of any type of data, and returns the current object itself.public String toString()
: The current StringBuilder object to a String object.
append method
overloads append a variety of methods that can receive any type of parameter. Any data will be added as a parameter string corresponding to the content to the StringBuilder. E.g:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("a").append("b");
System.out.println(stringBuilder);
//ab
Note: StringBuilder has overwritten the Object toString method among.
toString method
By toString method, StringBuilder String object will be converted to immutable objects. Such as:
StringBuilder sb = new StringBuilder("Hello").append("World").append("Java");
// 调用方法
String str = sb.toString();
System.out.println(str); // HelloWorldJava