Detailed Java string buffer StringBuffer class usage _java

Source: Internet
Author: User
Tags memory usage object object stringbuffer

StringBuffer is a thread-safe, variable sequence of characters. It inherits from Abstractstringbuilder and implements the Charsequence interface.
StringBuilder is also a subclass of Abstractstringbuilder, but StringBuilder and stringbuffer are not thread-safe, the latter are thread-safe.
The diagram between StringBuffer and Charsequence is as follows:

The StringBuffer class, like String, is also used to represent strings, but because StringBuffer are implemented in a different way than string, StringBuffer does not generate new objects when string processing. superior to the string class in memory usage.
Therefore, in actual use, if you often need to modify a string, such as INSERT, delete, and other operations, the use of stringbuffer to be more appropriate.
There are many methods in the StringBuffer class that are the same as string classes, which are functionally identical to those in the string class.
One of the most notable differences, however, is that each modification of the StringBuffer object changes the object itself, which is the biggest difference from the string class.

In addition, because the StringBuffer is thread-safe, the concept of thread on the follow-up has a special chapter to introduce, so in multithreaded programs can also be very convenient to use, but the implementation of the program efficiency is relatively slow.

Initialization of 0.StringBuffer objects

The initialization of a StringBuffer object is not the same as the initialization of a string class, Java provides a special syntax, and typically the constructor is used for initialization.
For example:

StringBuffer s = new StringBuffer ();

The StringBuffer object initialized 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 this initialized StringBuffer object is the string "abc".
It should be noted that StringBuffer and string are of different types and cannot be coerced directly, and the following code is wrong:

StringBuffer s = "abc";        The assignment type does not match
stringbuffer s = (stringbuffer) "ABC";  No inheritance relationship, no strong transfer

The code for the interchange 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 is converted to StringBuffer
string s1 = sb1.tostring ();       Convert StringBuffer to String

List of 1.StringBuffer functions

StringBuffer () stringbuffer (int capacity) StringBuffer (string string) StringBuffer (charsequence cs) StringBuffer Appen D (Boolean B) stringbuffer append (int i) StringBuffer append (long L) StringBuffer append (float f) stringbuffer append (d Ouble d) Synchronized stringbuffer append (char ch) synchronized StringBuffer append (char[] chars) synchronized Stringbuf  Fer append (char[] chars, int start, int length) synchronized stringbuffer (Object obj) append synchronized 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, in T end) Synchronized StringBuffer Deletecharat (int location) synchronized void ensurecapacity (int min) synchronized void getChars (int start, int e nd, char[] buffer, int idx) synchronized int indexOf (string subString, int start) int indexOf (string string) Stringbuffe R Insert (int index, Boolean b) stringbuffer insert (int index, int i) stringbuffer Insert (int index, long L) Stringbuffe R 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, CHARSEQUENC e s, int start, int end) int LastIndexOf (string string) synchronized int LastIndexOf (string subString, int start) int L Ength () 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 le ngth) synchronized charsequence subsequence (int start, int end) synchronized String substring (int start) synchronized St

 Ring substring (int start, int end) synchronized String toString () synchronized void TrimToSize ()

2. StringBuffer example
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 (); /** * StringBuffer Other API examples * * 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 related API demo/private static void Testindexapis () {System.out.println ("----------------- ---------------Testindexapis--------------------------------");
  StringBuffer Sbuilder = new StringBuffer ("Abcabcabcabcabcabcabcabc");

  System.out.printf ("sbuilder=%s\n", Sbuilder); 1.

  From the point of departure, find out the first occurrence of "BC" Position System.out.printf ("%-30s =%d\n", "Sbuilder.indexof (\" bc\ ")", Sbuilder.indexof ("BC")); 2. Starting from position 5, find out where "BC" first appears System.out.printf ("%-30s =%d\n", "Sbuilder.indexof" ("Bc\", 5) ", Sbuilder.indexof (" BC ", 5)

  ); 3.

  From the back forward, find out the first occurrence of "BC" Position System.out.printf ("%-30s =%d\n", "Sbuilder.lastindexof (\" bc\ ")", Sbuilder.lastindexof ("BC")); 4. Starting from position 4, from the back forward, find out the first occurrence of "BC" Position System.out.printf ("%-30s =%d\n", "Sbuilder.lastindexof (\" Bc\ ", 4)", Sbuilder.lastindexof

  ("BC", 4));
 System.out.println (); /** * StringBuffer replace () example/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 ("-----------------

  ---------------Testdeleteapis-------------------------------");

  StringBuffer Sbuilder = new StringBuffer ("0123456789");
  Deletes the character at position 0, and the remaining character is "123456789".
  Sbuilder.deletecharat (0);
  Deletes the character between position 3 (included) and the position 6 (not included), and the remaining character is "123789".

  Sbuilder.delete (3,6);
  Get SB to start with position 1 string str1 = sbuilder.substring (1);
  Get SB from position 3 (included) to position 5 (excluding) string str2 = Sbuilder.substring (3, 5);

  Gets the string from position 3 (included) to position 5 (not included) in SB, and the object is the Charsequence object, which transitions to string 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 (); /** * StringBuffer Insert () example/private static void Testinsertapis () {System.out.println ("-----------------

  ---------------Testinsertapis-------------------------------");

  StringBuffer Sbuilder = new StringBuffer ();
  Inserts a character array at position 0 sbuilder.insert (0, New char[]{' A ', ' B ', ' C ', ' d ', ' e '}); Inserts a character array at position 0.
  0 indicates the starting position of the character array, and 3 represents the length Sbuilder.insert (0, New char[]{' A ', ' B ', ' C ', ' D ', ' E '}, 0, 3);
  Insert float Sbuilder.insert (0, 1.414f) at position 0;
  Insert a double sbuilder.insert (0, 3.14159d) at position 0;
  Inserts a Boolean Sbuilder.insert (0, true) at position 0;
  Insert Char sbuilder.insert (0, ' \ n ') at position 0;
  Insert int Sbuilder.insert (0, 100) at position 0;
  Insert Long Sbuilder.insert (0, 12345L) at position 0;
  Insert the StringBuilder object Sbuilder.insert (0, New StringBuffer ("StringBuilder") at position 0); Inserts a StringBuilder object at position 0.
  6 indicates the starting position (including) at position 0 where the object is inserted, 13 is the ending position (excluding) Sbuilder.insert (0, New StringBuffer ("STRINGBUILDER"), 6, 13);
  Inserts a StringBuffer object at position 0. Sbuilder.iNsert (0, New StringBuffer ("StringBuffer")); Inserts a StringBuffer object at position 0.
  6 indicates the starting position (including) at position 0 where the object is inserted, 12 is the ending position (excluding) Sbuilder.insert (0, New StringBuffer ("StringBuffer"), 6, 12);
  Inserts a string object at position 0.
  Sbuilder.insert (0, "String"); Inserts a string object at position 0.
  1 indicates the starting position (including) at position 0 where the object is inserted, and 6 is the ending position (excluding) Sbuilder.insert (0, "0123456789", 1, 6);

  Sbuilder.insert (0, ' \ n '); Inserts an object at position 0.
  Here take HashMap as an example 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 () example/private static void Testappendapis () {System.out.println ("-----------------

  ---------------Testappendapis-------------------------------");

  StringBuffer Sbuilder = new StringBuffer ();
  Append character array sbuilder.append (new char[]{' A ', ' B ', ' C ', ' d ', ' e '}); Appends an array of characters.
  0 indicates the starting position of the character array, and 3 represents the length Sbuilder.append (new char[]{' A ', ' B ', ' C ', ' D ', ' E '}, 0, 3);
  Add 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")); Appends the StringBuilder object.
  6 indicates the starting position of the appended object (including), 13 is the end position (excluding) Sbuilder.append (new StringBuffer ("STRINGBUILDER"), 6, 13);
  Appends the StringBuffer object.
  Sbuilder.append (New StringBuffer ("StringBuffer")); Appends the StringBuffer object.
  6 indicates the starting position of the appended object (including), 12 is the end position (excluding) Sbuilder.append (new StringBuffer ("StringBuffer"), 6, 12);
  Appends a string object.
  Sbuilder.append ("String"); Appends a string object.
  1 indicates the starting position of the appended object (including), 6 is the end position (excluding) sbuilder.append ("0123456789", 1, 6);

  Sbuilder.append (' \ n '); Append Object object.
  Here 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 of "word" sbuilder.appendcodepoinT (0X7B26); 0X7B26 is the Unicode encoding Sbuilder.appendcodepoint (0X7F16) of "character"; 0x7f16 is a "codec" of the Unicode Encoding Sbuilder.appendcodepoint (0x7801);
 0x7801 is the "code" of the Unicode Encoding System.out.printf ("%s\n\n", Sbuilder);

 }
}

Run Result:

--------------------------------Testinsertapis-------------------------------{3=three, 2=two, 1=one} 12345stringbufferstringbufferbuilderstringbuilder12345100 TRUE3.141591.414ABCABCDE-----------------------------
---testappendapis-------------------------------abcdeabc1.4143.14159true 10012345stringbuilderbuilderstringbufferbufferstring12345 {3=three, 2=two, 1=one} character encoding---------------------------- ----Testreplaceapis------------------------------sbuilder=abcde3456789 sbuilder=9876543210 sbuilder=m123456789--
------------------------------Testdeleteapis-------------------------------sbuilder=123789 str1=23789 str2=78 str3=78--------------------------------Testindexapis--------------------------------sbuilder= ABCABCABCABCABCABCABCABC sbuilder.indexof ("BC") = 1 sbuilder.indexof ("BC", 5) = sbuilder.lastindexof ("BC") = SBU
Ilder.lastindexof ("BC", 4) = 4--------------------------------testotherapis--------------------------------cap=26 C=6 carr[0]=3 Carr[1]=4 carr[2]=5 carr[3]=6 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.