StringBuffer的capacity

二.用字符串初始化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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值