Class StringBuffer

本文详细介绍了StringBuffer类,它是Java中一个线程安全且可修改的字符序列类。StringBuffer允许在任意位置插入或追加字符,并能自动调整容量。文章对比了StringBuffer与StringBuilder的区别,强调了前者适用于多线程环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public final class StringBuffer extends Object implements SerializableCharSequence
A thread-safe,  mutable可变 sequence序列 of characters. A string buffer is like a  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实例 behaveas 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 areoverloaded重载 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 bufferperforming 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 newinternal内部 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 sameoperations操作 but it is faster, as it performs执行 no synchronization.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值