StringBuffer is a thread-safe, variable character sequence. It inherits from AbstractStringBuilder and implements the CharSequence interface.
StringBuilder is also a subclass inherited from AbstractStringBuilder; however, StringBuilder and StringBuffer are different. The former is non-thread-safe, while the latter is thread-safe.
The relationship diagram between StringBuffer and CharSequence is as follows:
The StringBuffer class is like String and is also used to represent strings. However, because the internal implementation of StringBuffer is different from String, StringBuffer does not generate new objects when processing strings, and is better than String class in memory usage.
Therefore, when using it in actual use, if you often need to modify a string, such as insertion, deletion, etc., it is more suitable to use StringBuffer.
There are many methods in the StringBuffer class that are the same as the String class. These methods are functionally the same as the functions in the String class.
But there is one of the most significant differences in that each modification of the StringBuffer object changes the object itself, which is the biggest difference from the String class.
In addition, since StringBuffer is thread-safe, there are special chapters to introduce the concept of threads in the future, so it can also be used in multi-threaded programs, but the execution efficiency of the program is relatively slow.
0. Initialization of StringBuffer object
The initialization of a StringBuffer object is not like the initialization of a String class. Java provides special syntax, and under normal circumstances, it is generally used to initialize it using constructors.
For example:
StringBuffer s = new StringBuffer();
The StringBuffer object initialized in this way is an empty object.
If you need to create a StringBuffer object with content, you can use:
StringBuffer s = new StringBuffer("abc"); The content of the StringBuffer object initialized in this way is the string "abc".
It should be noted that StringBuffer and String are different types and cannot be cast directly. The following code is wrong:
StringBuffer s = "abc"; //The assignment type does not match StringBuffer s = (StringBuffer)"abc"; //There is no inheritance relationship and it is impossible to force the rotation.
The code for transmuting between the StringBuffer object and the String object is as follows:
String s = "abc";StringBuffer sb1 = new StringBuffer("123");StringBuffer sb2 = new StringBuffer(s); //String convert to StringBufferString s1 = sb1.toString(); //StringBuffer convert to String 1.StringBuffer function list
StringBuffer()StringBuffer(int capacity)StringBuffer(String string)StringBuffer(CharSequence cs)StringBuffer append(boolean b)StringBuffer append(int i)StringBuffer append(long l)StringBuffer append(float f)StringBuffer append(double d)synchronized StringBuffer append(char ch)synchronized StringBuffer append(char[] chars)synchronized StringBuffer append(char[] chars, int start, int length)synchronized StringBuffer append(Object obj)synchronized StringBuffer append(String string)synchronized StringBuffer append(StringBuffer sb)synchronized StringBuffer append(CharSequence s)synchronized StringBuffer append(CharSequence s, int start, int end)StringBuffer appendCodePoint(int codePoint)int capacity()synchronized char charAt(int index)synchronized int codePointAt(int index)synchronized int codePointBefore(int index)synchronized int codePointCount(int beginIndex, int endIndex)synchronized StringBuffer delete(int start, int end)synchronized StringBuffer deleteCharAt(int location)synchronized void ensureCapacity(int min)synchronized void getChars(int start, int end, char[] buffer, int idx)synchronized int indexOf(String subString, int start)int indexOf(String string)StringBuffer insert(int index, boolean b)StringBuffer insert(int index, int i)StringBuffer insert(int index, long l)StringBuffer insert(int index, float f)StringBuffer insert(int index, double d)synchronized StringBuffer insert(int index, char ch)synchronized StringBuffer insert(int index, char[] chars)synchronized StringBuffer insert(int index, char[] chars, int start, int length)synchronized StringBuffer insert(int index, String string)StringBuffer insert(int index, Object obj)synchronized StringBuffer insert(int index, CharSequence s)synchronized StringBuffer insert(int index, CharSequence s, int start, int end)int lastIndexOf(String string)synchronized int lastIndexOf(String subString, int start)int length()synchronized int offsetByCodePoints(int index, int codePointOffset)synchronized StringBuffer replace(int start, int end, String string)synchronized StringBuffer reverse()synchronized void setCharAt(int index, char ch)synchronized void setLength(int length)synchronized CharSequence subSequence(int start, int end)synchronized String substring(int start)synchronized String substring(int start, int end)synchronized String toString()synchronized void trimToSize()
2. StringBuffer example
The source code is as follows (StringBufferTest.java):
/** * StringBuffer demo program*/import java.util.HashMap;public class StringBufferTest { public static void main(String[] args) { testInsertAPIs() ; testAppendAPIs() ; testReplaceAPIs() ; testDeleteAPIs() ; testIndexAPIs() ; testOtherAPIs() ; } /** * Other API examples of StringBuffer*/ private static void testOtherAPIs() { System.out.println("-------------------------------- testOtherAPIs --------------------------------"); StringBuffer sbuilder = new StringBuffer("0123456789"); int cap = sbuilder.capacity(); System.out.printf("cap=%d/n", cap); char c = sbuilder.charAt(6); System.out.printf("c=%c/n", c); char[] carr = new char[4]; sbuilder.getChars(3, 7, carr, 0); for (int i=0; i<carr.length; i++) System.out.printf("carr[%d]=%c ", i, carr[i]); System.out.println(); System.out.println(); } /** * StringBuffer 中index相关API演示*/ private static void testIndexAPIs() { System.out.println("-------------------------------- testIndexAPIs --------------------------------"); StringBuffer sbuilder = new StringBuffer("abcAbcABCabCaBcAbCaBCabc"); System.out.printf("sbuilder=%s/n", sbuilder); // 1. From front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/")", sbuilder.indexOf("bc")); // 2. From position 5, from front to back, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.indexOf(/"bc/", 5)", sbuilder.indexOf("bc", 5)); // 3. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/")", sbuilder.lastIndexOf("bc")); // 4. From back to front, find the location where "bc" appears for the first time System.out.printf("%-30s = %d/n", "sbuilder.lastIndexOf(/"bc/", 4)", sbuilder.lastIndexOf("bc", 4)); System.out.println(); } /** * StringBuffer 的replace()示例*/ private static void testReplaceAPIs() { System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); StringBuffer sbuilder; sbuilder = new StringBuffer("0123456789"); sbuilder.replace(0, 3, "ABCDE"); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuffer("0123456789"); sbuilder.reverse(); System.out.printf("sbuilder=%s/n", sbuilder); sbuilder = new StringBuffer("0123456789"); sbuilder.setCharAt(0, 'M'); System.out.printf("sbuilder=%s/n", sbuilder); System.out.println(); } /** * StringBuffer delete() example*/ private static void testDeleteAPIs() { System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- sbuilder.deleteCharAt(0); // Delete characters between position 3 (including) and position 6 (excluding), and the remaining characters are "123789". sbuilder.delete(3,6); // Get the string starting from position 1 in sb String str1 = sbuilder.substring(1); // Get the string from position 3 (including) to position 5 (excluding) in sb String str2 = sbuilder.substring(3, 5); // Get the string from position 3 (including) to position 5 (excluding) in sb String str3 = (String)sbuilder.subSequence(3, 5); System.out.printf("sbuilder=%s/nstr1=%s/nstr2=%s/nstr3=%s/n", sbuilder, str1, str2, str3); System.out.println(); } /** * Insert() example of StringBuffer*/ private static void testInsertAPIs() { System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 0 represents the starting position of the character array, 3 represents the length sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); // Insert float sbuilder.insert(0, 1.414f); // Insert double sbuilder.insert(0, 3.14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 14159d); // Insert boolean sbuilder.insert(0, true); // Insert char sbuilder.insert(0, '/n'); // Insert int sbuilder.insert(0, 100); // Insert long sbuilder.insert(0, 12345L); // Insert the StringBuilder object sbuilder.insert(0, new StringBuffer("StringBuilder")); // Insert the StringBuilder object at position 0. 6 represents the start position (including) of the object inserted at position 0, 13 is the end position (excluding) sbuilder.insert(0, new StringBuffer("STRINGBUILDER"), 6, 13); // Insert the StringBuffer object at position 0. sbuilder.insert(0, new StringBuffer("StringBuffer")); // Insert the StringBuffer object at position 0. 6 represents the start position (including) of the object inserted at position 0, 12 is the end position (excluding) sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); // Insert the String object at position 0. sbuilder.insert(0, "String"); // Insert the String object at position 0. 1 represents the start position (including) of the object inserted at position 0, 6 is the end position (excluding) sbuilder.insert(0, "0123456789", 1, 6); sbuilder.insert(0, '/n'); // Insert the Object object at position 0.此处以HashMap为例HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.insert(0, map); System.out.printf("%s/n/n", sbuilder); } /** * StringBuffer 的append()示例*/ private static void testAppendAPIs() { System.out.println("-------------------------------- testAppendAPIs ----------------------------------"); StringBuffer sbuilder = new StringBuffer(); // Append character array sbuilder.append(new char[]{'a','b','c','d','e'}); // Append character array. 0 indicates the starting position of the character array, 3 indicates the length sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); // Append float sbuilder.append(1.414f); // Append double sbuilder.append(3.14159d); // Append boolean sbuilder.append(true); // Append char sbuilder.append('/n'); // Append int sbuilder.append(100); // Append long sbuilder.append(12345L); // Append StringBuilder object sbuilder.append(new StringBuffer("StringBuilder")); // Append StringBuilder object. 6 indicates the start position (including) of the appended object, 13 is the end position (excluding) sbuilder.append(new StringBuffer("STRINGBUILDER"), 6, 13); // Append StringBuffer object. sbuilder.append(new StringBuffer("StringBuffer")); // Append StringBuffer object. 6 indicates the start position (including) of the appended object, 12 is the end position (excluding) sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); // Append String object. sbuilder.append("String"); // Append String object. 1 indicates the start position (including) of the appended object, 6 is the end position (excluding) sbuilder.append("0123456789", 1, 6); sbuilder.append('/n'); // Append Object object. Here we take HashMap as an example HashMap map = new HashMap(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); sbuilder.append(map); sbuilder.append('/n'); // Append unicode encoding sbuilder.appendCodePoint(0x5b57); // 0x5b57 is the unicode encoding sbuilder.appendCodePoint(0x7b26); // 0x7b26 is the unicode encoding sbuilder.appendCodePoint(0x7f16); // 0x7f16 is the "encoded" unicode encoding sbuilder.appendCodePoint(0x7801); // 0x7801 is the "encoded" unicode encoding System.out.printf("%s/n/n", sbuilder); }} Running results:
-------------------------------- testInsertAPIs -------------------------------{3=three, 2=two, 1=one}12345StringBUFFERStringBufferBUILDERStringBuilder12345100true3.141591.414ABCabcde-------------------------------- testAppendAPIs -------------------------------abcdeABC1.4143.14159true10012345StringBuilderBUILDERStringBufferBUFFERString12345{3=three, 2=two, 1=one} character encoding ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------sbuilder=abcAbcABCabCaBcAbCaBCabcsbuilder.indexOf("bc") = 1sbuilder.indexOf("bc", 5) = 22sbuilder.lastIndexOf("bc") = 22sbuilder.lastIndexOf("bc", 4) = 4-------------------------------- testOtherAPIs --------------------------------cap=26c=6carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6