StringBuffer的问题

yanxibang 2004-10-17 03:19:13
StringBuffer buffer = new StringBuffer();
StringBuffer buffer = new StringBuffer(10);
第二个构造方法是什么意思.
...全文
151 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
同意楼上,默认的大小是 16!
边城狂人 2004-10-17
  • 打赏
  • 举报
回复
看 StringBuffer 的源码,如果在需要“扩容”的时候,会调用如下方法

void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
char newValue[] = new char[newCapacity];
System.arraycopy(value, 0, newValue, 0, count);
value = newValue;
}

这个方法中,实际上是对当前容量扩大一倍,并且保证最大长度在整数范围内。然后产生一个新的数组,将原来的内容拷贝过去。所以,在扩容的时候是会有拷贝数据的操作,这个操作还会对性能稍有影响,如果,在构造一个 StringBuffer 的时候如果能指定一个正确的大小,使之不需要频繁扩容,那是最好的。默认的大小好像是 16。
intelserver 2004-10-17
  • 打赏
  • 举报
回复
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.

会自动增大,没看到说会影响性能

pankun 2004-10-17
  • 打赏
  • 举报
回复
指定初始容量的
miaoliujun 2004-10-17
  • 打赏
  • 举报
回复
能够,但影响性能
yanxibang 2004-10-17
  • 打赏
  • 举报
回复
指定初始容量???如果添加字符数超过的话它的初始值,它是不是能自动扩大
intelserver 2004-10-17
  • 打赏
  • 举报
回复
StringBuffer(int length)
Constructs a string buffer with no characters in it and an initial capacity specified by the length argument

length指定初始容量
mbl 2004-10-17
  • 打赏
  • 举报
回复
区域大小

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧