Java中的StringBuffer

StringBuffer in java is used to create modifiable String objects. This means that we can use StringBuffer to append, reverse, replace, concatenate and manipulate Strings or sequence of characters. Corresponding methods under StringBuffer class are respectively created to adhere to these functions.

Java中的StringBuffer用于创建可修改的String对象。 这意味着我们可以使用StringBuffer追加,反转,替换,连接和操作字符串或字符序列。 分别创建StringBuffer类下的相应方法以遵守这些功能。

In Java, Strings are known to be immutable or un-editable, unless overwritten upon. This is where StringBuffer class comes into picture, where it can accommodate character sequences and still enable a mutable feature.

在Java中,除非重写,否则字符串是不可变的或不可编辑的。 这就是StringBuffer类出现的地方,它可以容纳字符序列并仍启用可变功能。

Java中的StringBuffer (StringBuffer in Java)

Some important points about StringBuffer in java are:

Java中有关StringBuffer的一些重要点是:

  • StringBuffer is much alike the String class, but with mutability features.

    StringBuffer与String类非常相似,但具有可变性功能。
  • Unlike Strings where the length and memory allocation are final, StringBuffer has existing methods to modify these properties.

    与Strings的长度和内存分配是最终的不一样,StringBuffer具有修改这些属性的现有方法。
  • StringBuffer is thread safe, most of it’s methods are synchronized. So StringBuffer object can’t be accessed or used by multiple threads at the same time.

    StringBuffer是线程安全的,大多数方法都是同步的。 因此,多个线程不能同时访问或使用StringBuffer对象。
  • java.lang.StringBuffer extends AbstractStringBuilder abstract class.

    java.lang.StringBuffer扩展AbstractStringBuilder抽象类。
  • StringBuffer inherits clone(), equals(), finalize(), getClass(), hashCode(), notify() and notifyAll() methods from java.lang.Object super class.

    StringBuffer从java.lang.Object超类继承了clone()equals()finalize()getClass()hashCode()notify()notifyAll()方法。
  • StringBuffer implements CharSequence, Appendable and Serializable interfaces.

    StringBuffer实现CharSequenceAppendableSerializable接口。
  • StringBuffer capacity() method can be used to retrieve the memory available for new character sequences to be added, beyond which the allocation will occur.

    StringBuffer Capacity capacity()方法可用于检索可用于添加新字符序列的内存,超出该范围将进行分配。
  • Compared to StringBuilder Class, StringBuffer operates slower due to synchronization.

    与StringBuilder类相比,StringBuffer由于同步而运行较慢。

Java StringBuffer class features the flexibility of character sequence memory allocation. This means we can modify the given String using StringBuffer class. What makes this possible is that StringBuffer class reserves contingent memory for future modification.

Java StringBuffer类具有字符序列内存分配的灵活性。 这意味着我们可以使用StringBuffer类修改给定的String。 使之成为可能的原因是StringBuffer类保留了临时内存以供将来修改。

StringBuffer类图 (StringBuffer Class Diagram)

Below image illustrates the interfaces implemented by StringBuffer class. Notice that StringBuffer extends AbstractStringBuilder class that was introduced in Java 1.5 when StringBuilder was also introduced.

下图说明了StringBuffer类实现的接口。 请注意,StringBuffer扩展了Java 1.5中引入StringAbstracter时引入的AbstractStringBuilder类。

StringBuffer构造函数 (StringBuffer Constructors)

  1. StringBuffer(): Creates a StringBuffer with empty content and 16 reserved characters by default.
    StringBuffer sb = new StringBuffer();

    StringBuffer() :默认情况下,创建一个具有空内容和16个保留字符的StringBuffer。
  2. StringBuffer(int sizeOfBuffer): Creates a StringBuffer with the passed argument as the size of the empty buffer.
    StringBuffer sb = new StringBuffer(20);

    StringBuffer(int sizeOfBuffer) :创建一个StringBuffer,其中传递的参数为空缓冲区的大小。
  3. StringBuffer(String string): Creates a StringBuffer with the passed String as the initial content of the buffer. 16 contingent memory characters are pre-allocated, not including the buffer, for modification purposes.
    StringBuffer sb = new StringBuffer("Hello World!");

    StringBuffer(String string) :创建一个StringBuffer,将传递的String作为缓冲区的初始内容。 为了修改目的,预先分配了16个或有内存字符,不包括缓冲区。

StringBuffer方法 (StringBuffer Methods)

  1. length(): Returns the StringBuffer object’s length.

    length() :返回StringBuffer对象的长度。
  2. capacity(): Returns the capacity of the StringBuffer object.

    capacity() :返回StringBuffer对象的容量。
  3. package com.journaldev.java;
    
    public class StringBufferExample {
    
    	public static void main(String[] args) {
    		StringBuffer sb = new StringBuffer("Hello");
    		int sbLength = sb.length();
    		int sbCapacity = sb.capacity();
    		System.out.println("String Length of " + sb + " is " + sbLength);
    		System.out.println("Capacity of " + sb + " is " + sbCapacity);
    	}
    
    }

    Output produced by above StringBuffer example program:

    上面的StringBuffer示例程序产生的输出:

    String Length of Hello is 5
    Capacity of Hello is 21
  4. append(): appends the specified argument string representation at the end of the existing String Buffer. This method is overloaded for all the primitive data types and Object.

    append() :将指定的参数字符串表示形式追加到现有字符串缓冲区的末尾。 所有原始数据类型和对象都重载了此方法。
  5. StringBuffer sb = new StringBuffer("Hello ");
    
    sb.append("World ");
    
    sb.append(2017);
    
    System.out.println(sb);

    Output: Hello World 2017

    产出 :Hello World 2017

  6. insert(): insert() method takes two parameters – the index integer value to insert a value and the value to be inserted. The index tells StringBuffer where to insert the passed character sequence. Again this method is overloaded to work with primitive data types and Objects.

    insert() :insert()方法采用两个参数-用于插入值的索引整数值和要插入的值。 索引告诉StringBuffer在哪里插入传递的字符序列。 同样,此方法已重载以使用原始数据类型和对象。
  7. StringBuffer sb = new StringBuffer("HelloWorld ");
    
    sb.insert(5, " ");
    
    sb.insert(sb.length(), 2017);
    
    System.out.println(sb);

    Output: Hello World 2017

    产出 :Hello World 2017

  8. reverse(): Reverses the existing String or character sequence content in the buffer and returns it. The object must have an existing content or else a NullPointerException is thrown.

    reverse():反转缓冲区中现有的String或字符序列的内容并返回它。 该对象必须具有现有内容,否则将引发NullPointerException
  9. StringBuffer sb = new StringBuffer("Hello World");
    
    System.out.println(sb.reverse());

    Output: dlroW olleH

    输出 :dlroW olleH

  10. delete(int startIndex, int endIndex): accepts two integer arguments. The former serves as the starting delete index and latter as the ending delete index. Therefore the character sequence between startIndex and endIndex–1 are deleted. The remaining String content in the buffer is returned.

    delete(int startIndex, int endIndex) :接受两个整数参数。 前者充当开始删除索引,后者充当结束删除索引。 因此,startIndex和endIndex-1之间的字符序列将被删除。 返回缓冲区中剩余的String内容。
  11. StringBuffer sb = new StringBuffer("Hello World");
    
    System.out.println(sb.delete(5,11)); //prints Hello
  12. deleteCharAt(int index): deletes single character within the String inside the buffer. The location of the deleted character is determined by the passed integer index. The remaining String content in the buffer is returned.

    deleteCharAt(int index) :删除缓冲区内String中的单个字符。 删除字符的位置由传递的整数索引确定。 返回缓冲区中剩余的String内容。
  13. StringBuffer sb = new StringBuffer("Hello World!");
    
    System.out.println(sb.deleteCharAt(11)); //prints "Hello World"
  14. replace(int startIndex, int endIndex, String str): Accepts three arguments: first two being the starting and ending index of the existing String Buffer. Therefore the character sequence between startIndex and endIndex–1 are removed. Then the String passed as third argument is inserted at startIndex.

    replace(int startIndex, int endIndex, String str) :接受三个参数:前两个参数是现有字符串缓冲区的开始和结束索引。 因此,删除了startIndex和endIndex-1之间的字符序列。 然后,将作为第三个参数传递的String插入到startIndex处。
  15. StringBuffer sb = new StringBuffer("Hello World!");
    
    System.out.println(sb.replace(6,11,"Earth")); //prints "Hello Earth!"

That’s all for StringBuffer in Java. Most of the time we don’t need to use StringBuffer because String is immutable and we can use StringBuilder in single threaded environments. You should use StringBuffer only when multiple threads are modifying it’s contents.

Java的StringBuffer就是这样。 大多数时候,我们不需要使用StringBuffer,因为String是不可变的,我们可以在单线程环境中使用StringBuilder。 仅当多个线程修改它的内容时,才应使用StringBuffer。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16827/stringbuffer-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值