Java——StringBuffer和StringBuilder

The difference between StringBuffer and StringBuilder class of

Talk about StringBuffer class and StringBuilder We have to look back at the String class, is a Java-based and important class, and String is a typical implementation Immutable class is declared final class, in addition to hash this property other properties are declared as final, because it non-denatured, for example, string concatenation when it will have a lot of useless intermediate objects, if such operations frequently have an impact on performance. Therefore leads StringBuffer.
StringBuffer append and offer add method, you can add a string to the end of the existing sequence or specific location, and its essence is a thread safe to modify the sequence of characters, all data modification methods are added synchronized. But to ensure the security thread is the need of the price performance of.
In many cases we do not need thread-safe string concatenation operation, this time on stage StringBuilder, and StringBuffer StringBuilder no difference on nature, is to remove that part of the thread-safe, reducing overhead. The use of both is essentially no difference, but on the issue of security in the development of tangled and norms.

  • A brief summary of
    StringBuffer is thread-safe low efficiency of
    high efficiency StringBuilder is not thread-safe

StringBuffer features

  • Once defined the string length is immutable. If a large number + fight string, more waste of space. So Java for our characters splicing operation convenient, provides us with a StringBuffer class.
  • Thread-safe variable sequence of characters. String String is similar to a buffer, but can not be modified, but can be changed and contents of the length of the sequence by some method.

Common construction method

  • Empty argument constructor
    public StringBuffer()
    //构造一个其中不带字符的字符串缓冲区,其初始容量为16个字符。
  • There arg constructor
    public StringBuffer(String str)
    //构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。

commonly used ways


public int capacity() //获取容量的理论值

public int length()// 获取长度的实际值

public StringBuffer append(String str)
//可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身

public StringBuffer insert(int offset,String str) 
//在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

public StringBuffer deleteCharAt(int index)
//删除指定位置的字符,并返回本身
public StringBuffer delete(int start,int end)
//删除从指定位置开始指定位置结束的内容,并返回本身

public StringBuffer replace(int start,int end,String str):
//从start开始到end用str替换

public String substring(int start): 
//从指定位置截取到末尾
public String substring(int start,int end): 
//截取从指定位置开始到结束位置,包括开始位置,不包括结束位置

public int indexOf(String str) 
//返回第一次出现的指定子字符串在该字符串中的索引。
public int indexOf(String str, int fromIndex) 
//从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引。

public StringBuffer reverse()
//字符串反转

发布了15 篇原创文章 · 获赞 8 · 访问量 1万+

Guess you like

Origin blog.csdn.net/Junzizhiai/article/details/102789441