StringBuffer() 
api中说:构造一个其中不带字符的字符串缓冲区,其初始容量为 16 个字符。
StringBuffer sb=new StringBuffer();//超过默认容量了,也不提示错误
sb.append("1");
............
sb.append("100");StringBuffer sb=new StringBuffer(10);//超过容量了,不提示错误
sb.append("1");
............
sb.append("100");
增加到100不提示错误,已经超过了16啊.请问是为什么啊?

解决方案 »

  1.   

    class A
    {
    public static void main(String args[])
    {
    StringBuffer sb=new StringBuffer(1);
    sb.append("a");
    sb.append("b");
            System.out.println(sb.capacity());返回4是什么意思啊?
    }
    }
      

  2.   

    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.
    也就是说如果超过默认容量,StringBuffer会自动增长
      

  3.   

    StringBuffer是可自动增长的
    sb.capacity()表示当前可放字符串长度,超过这个值,StringBuffer容量自动增加
      

  4.   

    sb.capacity() 当前StringBuffer 可存储字符串的总长度,sb.append(string),如果现有长度与于string长度的和小于 (sb.capacity()+1)*2 的话,那么现在的sb.capacity() 就增长到(sb.capacity()+1)*2,如果大于,sb.capacity() 就为未增加string之前的长度+string的长度
      

  5.   

    哦,原来如此啊?那么:
    StringBuffer sb=new StringBuffer(1);//这样不是更好吗?可以节省内存啊?为什么别人不这么产生对象呢?
      

  6.   

    You create the StringBuffer object just to use, why care the init size?
      

  7.   

    回楼上的,每次扩展容量消耗很大,StringBuffer本质上和数组也是差别不大的,可以认为是一个固定大小的String,每次超过了就新建一个更大的,这样反复初始化,反复拷贝原来的过去,效率是很低的,所以需要多大的尽量事先指定好。
      

  8.   

    楼上说的很有道理,补充下。它的APPENT性能相对比STRING+STRING高。
      

  9.   

    所以需要多大的尽量事先指定好,
    即StringBuffer sb = new StringBuffer(n);
    n尽量接近可能分配的内存的最大值。append当然比+快,是直接填充内存空间,而不是新建并拷贝。