Java StringBuilder class is mutable sequence of characters. StringBuilder Class can be comparable to String however the StringBuilder class provides more versatility because of its modification features.

Java StringBuilder类是可变的字符序列。 StringBuilder类可以与String相提并论,但是StringBuilder类由于其修改功能而提供了更多的通用性。

Java StringBuilder (Java StringBuilder)

  • StringBuilder class provides an API similar to StringBuffer, but unlike StringBuffer, it doesn’t guarantee thread safety.StringBuilder类提供类似于StringBuffer的API,但是与StringBuffer不同,它不能保证线程安全。
  • Java StringBuilder class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case).Java StringBuilder类设计用于在单个线程正在使用字符串缓冲区的地方(通常是这种情况)代替StringBuffer。
  • If execution speed and performance is a factor, StringBuilder class can be used in place of StringBuffer.如果执行速度和性能是一个因素,则可以使用StringBuilder类代替StringBuffer。
  • The bread-and-butter operations provided by the StringBuilder Class are the append() and insert() methods. These methods are overloaded within StringBuilder in order to accommodate different data type.StringBuilder类提供的基本操作是append()insert()方法。 为了容纳不同的数据类型,这些方法在StringBuilder中被重载。
  • The general process flow of StringBuilder append and insert methods is: (1) converts a given data to a string then (2) appends or inserts the characters of that string to the string builder. Java StringBuilder append() method always adds these characters at the end of the builder; insert() method inserts character(s) at a specified point.StringBuilder追加和插入方法的一般处理流程是:(1)将给定的数据转换为字符串,然后(2)将该字符串的字符追加或插入到字符串生成器。 Java StringBuilder append()方法始终将这些字符添加到生成器的末尾。 insert()方法在指定点插入字符。

StringBuilder类图 (StringBuilder Class Diagram)

StringBuffer和StringBuilder (StringBuffer and StringBuilder)

.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-baqh{text-align:center;vertical-align:top} .tg .tg-yw4l{vertical-align:top}.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-baqh{text-align:center;vertical-align:top} .tg .tg-yw4l{vertical-align:top}

StringBuffer StringBuilder
Synchronized, hence thread safe. Not synchronized, not thread safe.
Operates slower due to thread safety feature Better performance compared to StringBuffer
Has some extra methods – substring, length, capacity etc. Not needed because these methods are present in String too.
Introduced in Java 1.2 Introduced in Java 1.5 for better performance.
StringBuffer StringBuilder
同步,因此线程安全。 不同步,线程不安全。
由于具有线程安全功能,因此运行速度较慢 与StringBuffer相比,性能更好
有一些额外的方法–子字符串,长度,容量等。 不需要,因为这些方法也存在于String中。
在Java 1.2中引入 在Java 1.5中引入了更高的性能。

Java StringBuilder构造函数 (Java StringBuilder Constructors)

Constructor Description
StringBuilder() Creates an empty string builder with a default capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.
建设者 描述
StringBuilder() 创建一个默认容量为16(16个空元素)的空字符串生成器。
StringBuilder(CharSequence CS) 构造一个字符串生成器,其中包含与指定CharSequence相同的字符,以及在CharSequence后面附加的16个空元素。
StringBuilder(int initCapacity) 创建具有指定初始容量的空字符串构建器。
StringBuilder(String s) 创建一个字符串生成器,其值由指定的字符串初始化,并在该字符串后附加16个空元素。

StringBuilder的长度和容量 (StringBuilder Length and Capacity)

Java StringBuilder class, much like the String class, has length() method that returns the length of the character sequence in the builder.

Java StringBuilder类与String类非常相似,具有length()方法,该方法返回构建器中字符序列的长度。

However, StringBuilder inherits capacity() method from its superclass AbstractStringBuilder, that returns the number of character spaces that have been allocated. The returned value is always greater than or equal to the length (usually greater than) and automatically expands whenever necessary to accommodate character additions to the string builder.

但是,StringBuilder从其超类AbstractStringBuilder继承了Capacity capacity()方法,该方法返回已分配的字符空间的数量。 返回的值始终大于或等于长度(通常大于),并在需要时自动扩展以适应向字符串生成器添加字符。

// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();// adds 5 character string at beginning
sb.append("Hello");System.out.println("StringBuilder length = "+sb.length()); // prints 5
System.out.println("StringBuilder capacity = "+sb.capacity()); // prints 16

There are couple of other methods related to StringBuilder length and capacity.

还有其他几种与StringBuilder的长度和容量有关的方法。

  1. void setLength(int newLength): Sets the length of the character sequence. If newLength is less than length(), the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added at the end of the character sequence.void setLength(int newLength) :设置字符序列的长度。 如果newLength小于length(),则字符序列中的最后一个字符将被截断。 如果newLength大于length(),则在字符序列的末尾添加空字符。
  2. void ensureCapacity(int minCapacity): Ensures that the capacity is at least equal to the specified minimum.void ensureCapacity(int minCapacity) :确保容量至少等于指定的最小值。

StringBuilder methods like append(), insert() or setLength() can increase the length of the character sequence in the string builder so that the returned value of length() would be greater than the current capacity(). In this case, the capacity is automatically increased.

诸如append()insert()setLength()类的StringBuilder方法可以增加字符串生成器中字符序列的长度,以便返回的length()值大于当前的Capacity()。 在这种情况下,容量会自动增加。

Java StringBuilder示例 (Java StringBuilder Example)

Let’s see the examples of different methods of StringBuilder class.

让我们看一下StringBuilder类的不同方法的示例。

  1. append(): The StringBuilder append() method concatenates or attaches the passed String argument with the existing declared string. It attaches it after the declared string.

    package com.journaldev.java;public class StringBuilderExample {public static void main(String[] args) {StringBuilder sb = new StringBuilder("Hello ");sb.append("World");// now original string is changedSystem.out.println(sb);// prints Hello World}}

    Output: Hello World

    append() :StringBuilder append()方法将传递的String参数与现有声明的字符串连接或附加。 它将其附加在声明的字符串之后。

    输出 :Hello World

  2. insert(): StringBuilder insert() method inserts the passed String argument at the passed String index.
    StringBuilder sb = new StringBuilder("HellWorld");sb.insert(4, "o ");
    System.out.println(sb);// prints Hello World

    insert() :StringBuilder insert()方法将通过的String参数插入到通过的String索引处。

  3. replace(int startIndex, int endIndex, String str): StringBuilder replace() method replaces the existing declared string. String replacement occurs from the passed startingIndex up to the endingIndex.
    StringBuilder sb = new StringBuilder("Hello World!");sb.replace(6,11,"Earth");System.out.println(sb);// prints Hello Earth!

    replace(int startIndex, int endIndex, String str) :StringBuilder replace()方法替换现有已声明的字符串。 字符串替换发生在从传递的startingIndex到EndingIndex的范围内。

  4. delete(int startIndex, int endIndex): StringBuilder delete() method deletes a character or sets of characters. Deletion occurs at passed startingIndex up to endingIndex.
    StringBuilder sb = new StringBuilder("JournalDev.com");sb.delete(7,14);System.out.println(sb);// prints Journal

    delete(int startIndex, int endIndex) :StringBuilder delete()方法删除一个字符或一组字符。 删除发生在传递的startingIndex到endingIndex之间。

  5. reverse(): The reverse() method of StringBuilder class reverses the existing declared string. Invoking a reverse() method on a StringBuilder object with no existing declared value throws NullPointerException.
    StringBuilder sb = new StringBuilder("lived");sb.reverse();System.out.println(sb);// prints devil

    reverse() :StringBuilder类的reverse()方法将反转现有的声明字符串。 在没有现有声明值的StringBuilder对象上调用reverse()方法将引发NullPointerException 。

  6. capacity(): The capacity() method of StringBuilder class returns the current capacity of the StringBuilder object. The default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2=34.
    StringBuilder sb=new StringBuilder();  System.out.println(sb.capacity()); // default value 16  sb.append("Java");
    System.out.println(sb.capacity()); // still 16  sb.append("Hello StringBuilder Class!");
    System.out.println(sb.capacity()); // (16*2)+2

    capacity() :StringBuilder类的Capacity()方法返回StringBuilder对象的当前容量。 生成器的默认容量为16。如果字符数从其当前容量增加,则其容量将增加(old_capacity * 2)+2,例如,在当前容量为16时,它将变为(16 * 2)+ 2 = 34。

  7. ensureCapacity(): The ensureCapacity() method of StringBuilder class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (old_capacity*2)+2 e.g. at current capacity 16, it becomes (16*2)+2 which is 34.
    package com.journaldev.java;public class StringBuilderExample {public static void main(String[] args) {StringBuilder sbObj=new StringBuilder();  System.out.println(sbObj.capacity());//default 16 sbObj.append("Java StringBuilder Class!");  System.out.println(sbObj.capacity());// capacity 34 sbObj.ensureCapacity(12);// no change  System.out.println(sbObj.capacity());//still 34  sbObj.ensureCapacity(60); // (34*2)+2 = 70 System.out.println(sbObj.capacity()); //70 }}

    ensureCapacity() :StringBuilder类的ensureCapacity()方法可确保给定容量为当前容量的最小值。 如果大于当前容量,则将容量增加(old_capacity * 2)+2,例如,在当前容量16时,它将变为(16 * 2)+2,即34。

That’s all for Java StringBuilder class. It’s a very useful class to work with Strings in java.

Java StringBuilder类就这些了。 在Java中使用Strings是一个非常有用的类。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16833/java-stringbuilder

Java StringBuilder相关推荐

  1. Java StringBuilder神话被揭穿

    神话 用加号运算符连接两个字符串是万恶之源 -匿名Java开发人员 注意 :此处讨论的测试的源代码可以在Github上找到 从大学时代起,我就学会了使用+运算符将Java中的String连接视为致命的 ...

  2. java stringbuilder 清空问题

    java stringbuilder 清空问题 我也是碰到了这个问题才开始研究的,网上答案偏多,并且时间范围也比较大,各个版本的java 优化也不清楚,只能说我的java环境是1.7,测试给大家看. ...

  3. android stringbuilder 清空,java stringbuilder清空的方法

    java stringbuilder清空的三种方法 1.新生成一个,旧的由系统自动回收 2.delete 方法 builder1.delete(0, builder.length()); 3.Leng ...

  4. java stringbuilder 替换字符串_java中的经典问题StringBuilder替换String

    遇到一个面试题:在下面的例子中用"+"运算符连接字符串与用StringBuilder对象的append方法连接字符串哪个性能比较优异. 下图是给出的例子,例一,使用"+& ...

  5. java stringbuilder换行_初遇Java StringBuffer 和 StringBuilder 类利用 StringBuilder 给TextView实现换行处理...

    当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类. 和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够 ...

  6. Java StringBuilder getChars()方法与示例

    StringBuilder类的getChars()方法 (StringBuilder Class getChars() method) getChars() method is available i ...

  7. Java StringBuilder codePointAt()方法与示例

    StringBuilder类codePointAt()方法 (StringBuilder Class codePointAt() method) codePointAt() method is ava ...

  8. Java StringBuilder subSequence()方法与示例

    StringBuilder类subSequence()方法 (StringBuilder Class subSequence() method) subSequence() method is ava ...

  9. Java StringBuilder codePointCount()方法与示例

    StringBuilder类codePointCount()方法 (StringBuilder Class codePointCount() method) codePointCount() meth ...

最新文章

  1. Python自动化开发学习13-堡垒机开发
  2. ROS系统实现 tf坐标系广播与监听
  3. 测试邮件系统需要做的准备工作
  4. python安装(原系统中已有python2)
  5. 以人为本、用“简”驭“繁”……统统都是新华三物联网的关键词儿!
  6. 潘多拉固件设置ipv6_(转)pandorabox固件+PPPOE拨号+IPV6
  7. 同济大学计算机保研名单,同济大学2021届保研率27.8%,主要保研本校、复交清国...
  8. js输入银行卡号,自动查询银行名称、银行卡类型
  9. python学习笔记(六):if语句之处理数据
  10. 物联网应用三个阶段,你在哪里?
  11. web邮箱和客户端的区别
  12. 拯救强迫症:Win11去除桌面快捷方式小箭头
  13. 【5G UP】5G QoS参数那点事儿
  14. 学生用计算机cf82es,计算器(fx-82ES)玩得好是可以很变态的(必看)(6页)-原创力文档...
  15. QObject::moveToThread: Current thread(...) is not the object`s thread. Cannot move to target thread(
  16. Mac 安装homebrew
  17. Oracle导入dmp数据
  18. 我说我精通字符串,面试官竟然问我Java中的String有没有长度限制!?
  19. 机器学习中的敏感性和特异性的概念
  20. box-shadow和颜色渐变

热门文章

  1. 获取PowerShell某个对象的所有命令
  2. 客户关系管理之会员管理(转)
  3. DataTable 和 DataView 的理解
  4. [转载] 知乎日报接口
  5. [转载] 【Java核心技术卷】关于除以0的计算
  6. 数据库一些开发者了解的操作
  7. E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/t
  8. 20169212《Linux内核原理及分析》第十二周作业
  9. 关于修改android studio的gradle目录
  10. delphi android路径 TPath 文件路径,文件管理