The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
StringBuilder
objects are like String
objects, except that they can be modified.StringBuilder
对象与String
对象类似,只是它们可以修改。Internally, these objects are treated like variable-length arrays that contain a sequence of characters.在内部,这些对象被视为包含字符序列的可变长度数组。At any point, the length and content of the sequence can be changed through method invocations.在任何时候,都可以通过方法调用更改序列的长度和内容。
Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance.除非字符串生成器在代码更简单(请参阅本节末尾的示例程序)或性能更好方面具有优势,否则应始终使用字符串。For example, if you need to concatenate a large number of strings, appending to a 例如,如果需要连接大量字符串,则附加到StringBuilder
object is more efficient.StringBuilder
对象更有效。
The StringBuilder
class, like the String
class, has a length()
method that returns the length of the character sequence in the builder.StringBuilder
类与String
类一样,具有一个length()
方法,用于返回生成器中字符序列的长度。
Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated.与字符串不同,每个字符串生成器也有一个容量,即已分配的字符空间数。The capacity, which is returned by the capacity()
method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.capacity()
方法返回的容量始终大于或等于长度(通常大于),并将根据需要自动扩展以适应字符串生成器的添加。
StringBuilder() |
|
StringBuilder(CharSequence cs) |
CharSequence , plus an extra 16 empty elements trailing the CharSequence .CharSequence 相同的字符,并在CharSequence 后面附加16个空元素。 |
StringBuilder(int initCapacity) |
|
StringBuilder(String s) |
For example, the following code例如,下面的代码
// creates empty builder, capacity 16 StringBuilder sb = new StringBuilder(); // adds 9 character string at beginning sb.append("Greetings");
will produce a string builder with a length of 9 and a capacity of 16:将生成长度为9、容量为16的字符串生成器:
The StringBuilder
class has some methods related to length and capacity that the String
class does not have:StringBuilder
类有一些与String
类没有的长度和容量相关的方法:
void setLength(int newLength) |
newLength is less than length() , the last characters in the character sequence are truncated.newLength 小于length() ,则字符序列中的最后一个字符将被截断。newLength is greater than length() , null characters are added at the end of the character sequence.newLength 大于length() ,则在字符序列的末尾添加空字符。 |
void ensureCapacity(int minCapacity) |
A number of operations (for example, 许多操作(例如,append()
, insert()
, or setLength()
) can increase the length of the character sequence in the string builder so that the resultant length()
would be greater than the current capacity()
.append()
、insert()
或setLength()
)可以增加字符串生成器中字符序列的长度,从而使结果length()
大于当前capacity()
。When this happens, the capacity is automatically increased.发生这种情况时,容量会自动增加。
StringBuilder
操作The principal operations on a StringBuilder
that are not available in String
are the append()
and insert()
methods, which are overloaded so as to accept data of any type.StringBuilder
上在String
中不可用的主要操作是append()
和insert()
方法,它们被重载以接受任何类型的数据。Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder.每个参数都将其参数转换为字符串,然后将该字符串的字符追加或插入到字符串生成器中的字符序列中。The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.append
方法始终在现有字符序列的末尾添加这些字符,而insert
方法在指定点添加这些字符。
Here are a number of the methods of the 下面是StringBuilder
class.StringBuilder
类的一些方法。
StringBuilder append(boolean b) |
|
StringBuilder delete(int start, int end) |
StringBuilder 's char sequence.StringBuilder 字符序列中从start 到end-1 (包括)的子序列。index .index 处的字符。 |
StringBuilder insert(int offset, boolean b) |
|
StringBuilder replace(int start, int end, String s) |
|
StringBuilder reverse() |
|
String toString() |
String
method on a StringBuilder
object by first converting the string builder to a string with the toString()
method of the StringBuilder
class.StringBuilder
类的toString()
方法将字符串生成器转换为字符串,可以在StringBuilder
对象上使用任何字符串方法。StringBuilder(String str)
constructor.StringBuilder(String str)
构造函数将字符串转换回字符串生成器。
The 标题为“Strings”的部分中列出的StringDemo
program that was listed in the section titled "Strings" is an example of a program that would be more efficient if a StringBuilder
were used instead of a String
.StringDemo
程序是一个示例,如果使用StringBuilder
而不是字符串,则该程序的效率会更高。
StringDemo
reversed a palindrome.StringDemo
反转了回文。Here, once again, is its listing:这里再次列出:
public class StringDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an // array of chars for (int i = 0; i < len; i++) { tempCharArray[i] = palindrome.charAt(i); } // reverse array of chars for (int j = 0; j < len; j++) { charArray[j] = tempCharArray[len - 1 - j]; } String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); } }
Running the program produces this output:运行该程序会产生以下输出:
doT saw I was toD
To accomplish the string reversal, the program converts the string to an array of characters (first 为了完成字符串反转,程序将字符串转换为字符数组(第一个for
loop), reverses the array into a second array (second for
loop), and then converts back to a string.for
循环),将数组反转为第二个数组(第二个for
循环),然后再转换回字符串。
If you convert the 如果将回文字符串转换为字符串生成器,则可以在palindrome
string to a string builder, you can use the reverse()
method in the StringBuilder
class.StringBuilder
类中使用reverse()
方法。It makes the code simpler and easier to read:它使代码更简单,更易于阅读:
public class StringBuilderDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; StringBuilder sb = new StringBuilder(palindrome); sb.reverse(); // reverse it System.out.println(sb); } }
Running this program produces the same output:运行此程序会产生相同的输出:
doT saw I was toD
Note that 请注意,println()
prints a string builder, as in:println()
打印字符串生成器,如中所示:
System.out.println(sb);
because 因为sb.toString()
is called implicitly, as it is with any other object in a println()
invocation.sb.toString()
是隐式调用的,就像println()
调用中的任何其他对象一样。
StringBuffer
class that is exactly the same as the StringBuilder
class, except that it is thread-safe by virtue of having its methods synchronized.StringBuffer
类与StringBuilder
类完全相同,只是它通过同步其方法而具有线程安全性。