StringBuffer的capacity

来源:互联网 发布:长江航运 知乎 编辑:程序博客网 时间:2024/05/10 01:20

二.用字符串初始化StringBuffer的内容

在声明一个StringBuffer变量的时候,用字符串进行初始化,容量会有变化么?

例2:

// 声明并初始化 
StringBuffer sb1  =   new  StringBuffer( " hello world "  );
System.out.println(
 " with characters, the capacity of StringBuffer is  "   +
   sb1.capacity());
System.out.println(
 " but the length of the StringBuffer is  "   +
  sb1.length()); 
StringBuffer的capacity
// 利用append()来设置StringBuffer的内容
 
StringBuffer sb11  =   new  StringBuffer();
sb11.append(
 " hello world "
 );
System.out.println(
 " with append(), the capacity of StringBuffer is  "   +
  sb11.capacity());
System.out.println(
 " but the length of the StringBuffer is  "   +  sb11.length());


两者输出结果会一样么?
你一定认为,这不是显然的么。用长度为11的字符串“hello world”进行初始化,其长度11小于StringBuffer的默认容量16。所以两者结果都为capacity=16,length=11。
那么实际结果如何呢?

输出:

with characters, the capacity of StringBuffer is 27
but the length of the StringBuffer is 11
with append(), the capacity of StringBuffer is 16
but the length of the StringBuffer is 11

疑问:
怎么第一种方法的StringBuffer的capacity是27(16+11)呢?

原因:
StringBuffer的带参数的构造函数

1 public  StringBuffer(String str) {
2       this(str.length() + 16
 );
3       
 append(str);
4 }

结论: 
StringBuffer的capacity等于用来初始化的字符串长度(11)加上StringBuffer的默认容量(16),而不是我们想当然的在默认容量16中拿出11个来存放字符串“hello world”。
如果我们不设置StringBuffer的capacity,分别对两者继续追加字符串,任其自动增长,其容量增长如下:
第一种情况:27,56,114,230,462,926...,
第二种情况:16,34,70  ,142,286,574...,
(为什么容量增加会是这种规律,后面会做解释)。

我想情况2节省空间的概率大一些,因为StringBuffer的capacity的增长比情况1慢,每次增加的空间小一些。
所以以后写代码的时候可以考虑使用第二种方法(使用StringBuffer的append()),特别是初始化字符串很长的情况。当然这会多写一行代码^+^:

0 0
原创粉丝点击