String
, but can be modified. At
any point in time (
任何时候 ) it contains some
particular (
特定的 ) sequence of characters, but the length and content of the sequence can be changed through
certain (
某些 ) method
calls (
调用 ).
String buffers are safe for use by multiple threads. The methods are synchronized where necessary (必要的 ) so that all the operations on any particular instance behave as if they occur (发生 ) in some serial order that is consistent (一致的 ) with the order of the method calls made by each of the individual threads involved (涉及 ).
The principal (主要 ) operations (操作 ) on a StringBuffer
are the append
and insert
methods, which are overloaded so as to accept (接受 ) data of any type. Each effectively (有效 ) converts a given (特定 ) datum (基准 ) to a string and then appends or inserts the characters of that string to the string buffer. The append
method always adds these characters at the end of the buffer; the insert
method adds the characters at a specified point.
For example (例如 ), if z
refers (指 ) to a string buffer object whose (其 ) current contents are "start
", then the method call z.append("le")
would cause (导致 ) the string buffer to contain "startle
", whereas (而 ) z.insert(4, "le")
would alter the string buffer to contain "starlet
".
In general (一般 ), if sb refers to an instance (实例 ) of a StringBuffer
, then sb.append(x)
has the same effect (效果 ) as sb.insert(sb.length(), x)
.
Whenever (每当 ) an operation (操作 ) occurs involving a source sequence (such (比如 ) as appending or inserting from a source sequence) this class synchronizes only on the string buffer performing (执行 ) the operation, not on the source.
Every string buffer has a capacity (容量 ). As long as the length of the character sequence contained in the string buffer does not exceed (超过 ) the capacity (容量 ), it is not necessary (必要 ) to allocate (分配 ) a new internal (内部 ) buffer array. If the internal (内部 ) buffer overflows, it is automatically made larger. As of release JDK 5, this class has been supplemented (补充 ) with an equivalent (等价 ) class designed (设计 ) for use by a single thread, StringBuilder
. The StringBuilder class should generally (一般 ) be used in preference (优先 ) to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.