preface
In Java, a String is a constant that cannot be changed but can be shared once its value is created.
If we concatenate multiple strings, we open up a lot of space and waste a lot of memory space.
To solve this problem, we need to use the StringBuffer class and the StringBuilder class.
These two classes are awesome because they are both variable-length string classes, which greatly improve the efficiency of string concatenation.
StringBuffer is a StringBuilder
Common: The underlying data structures are all arrays of type char, mutable strings.
Differences: StringBuffer threads are safe to synchronize, but inefficient for multithreading. StringBuilder threads are out of sync, making multithreading less secure but more efficient.
Since both classes are used similarly, I’ll use the StringBuffer class as an example.
Class StringBuffer
StringBuffer class StringBuffer
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence{
Copy the code
Abstractstringbuffer class AbstractStringBuilder class, Serializable interface and CharSequence interface, both of which have two capabilities.
Three, four construction methods
public StringBuffer() {
super(16);
}
public StringBuffer(int capacity) {
super(capacity);
}
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
}
Copy the code
Focus on these two constructors:
Constructor: StringBuffer() Constructor: StringBuffer() Constructor: StringBuffer() Constructor: StringBuffer() constructor: StringBuffer()
Method description: Constructs a String buffer that is initialized to the contents of the specified String. The initial size is str.length() + 16.
Example:
package cn.tkr.demo;
public class MyStringBuffer {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer();
System.out.println("Sb1 character buffer size:"+ sb1.capacity()); StringBuffer sb2 = new StringBuffer("LoveJava");
System.out.println("Sb2 character buffer size:"+ sb2.capacity()); // Get the current StringBuffer size}}Copy the code
Running results:
Sb1 character buffer capacity: 16 SB2 character buffer capacity: 24Copy the code
Example Analysis: call the no-argument constructor, the initial capacity of sB1 character buffer is 16, call the argument constructor, the initial capacity is the length of the string (8) + 16, so the initial capacity is 24.
StringBuffer ()
Note: append (…). In the… Represents various types of arguments, such as append(int I), append(char c), append(String STR), etc
5. How does StringBuffer expand
Capacity expansion principle:
The underlying array structure of a StringBuffer uses an array of type char.
So, when we use the StringBuffer object append(…) Method appends data, and if the char array is too long to hold the data we append, the StringBuffer is expanded.
CopyOf (…) from the Arrays class is used for capacity expansion Method: Each capacity expansion is 2 times the original capacity plus 2.
Note: copyOf (…). In the… Represents various types of parameters, such as copyOf(int[] original, int newLength), copyOf(char[] original, int newLength), etc
Example source code analysis:
Suppose I now call the append (String STR) method and append a String (which is too long for the char array).
Append (String STR)
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
Copy the code
Method calls the append(String STR) method of the parent class via super.append(STR).
Append (String STR) ¶
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
Copy the code
So the important thing is that this ensureCapacityInternal(count + len) is a method that’s just scaling up, and the variable count is a global variable that doesn’t have an actual value, and len is the length of the string that we append to it.
That is, the length of the string we append is passed to the ensureCapacityInternal(int minimumCapacity) method.
EnsureCapacityInternal (int minimumCapacity)
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if(minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); }}Copy the code
MinimumCapacity refers to the length of the string appended, and value is the global char array name.
Minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value. length = minimumcapacity-value.
In this case, you need to use the copyOf(char[] Original, int newLength) method from the Arrays class.
Methods:
copyOf(char[] original, int newLength)
Description: Copies the specified array, truncates it, or populates it with the corresponding default values
The first argument to this method is the name of the source array, so value is passed.
The second argument is the length of the new array, which is returned by the newCapacity(int minCapacity) method.
NewCapacity (int minCapacity);
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
Copy the code
This method returns a new size (that is, the new array length), each increment of which is 2 times the original size plus 2.
The last
Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!