StringBuffer类-构造方法和StringBuffer中length()和capacity()区别

2022-07-11 13:48:42

一、构造方法

1、空参构造 new StringBuffer();

默认分配的初始化缓冲区的大小是16

源码:

   public StringBuffer() 
   {
      super(16);
   }

2、new StringBuffer(int capacity);

默认初始化缓冲区大小是其传入的值的大小

源码:

 public StringBuffer(int capacity) 
 {
    super(capacity);
 }

3.new StringBuffer(String str);

默认初始化缓冲区大小是16+str.length

源码:

 public StringBuffer(String str) 
 {
      super(str.length() + 16);
      append(str);
 }

4.new StringBuffer(CharSequence seq);

默认初始化缓冲区大小和3一样,都是

源码:

 public StringBuffer(CharSequence seq) 
 {
      this(seq.length() + 16);
      append(seq);
 }

二、StringBuffer中length()和capacity()区别
  length()方法返回当前StringBuffer的长度。capacity()方法返回当前系统分配得容量

public static void main(String[] args)
{
	StringBuffer sb = new StringBuffer(20);
	System.out.println(sb);
	System.out.println(sb.capacity());
	System.out.println(sb.length());
	sb.append("hello world , my name is ...");
	System.out.println(sb);
	System.out.println(sb.capacity());
	System.out.println(sb.length());
	sb.append("hello world , my name is ...");
	System.out.println(sb);
	System.out.println(sb.capacity());
	System.out.println(sb.length());
	
	StringBuffer sb2 = new StringBuffer();
	System.out.println(sb2);
	System.out.println(sb2.capacity());
	System.out.println(sb2.length());
	sb2.append("hello world , my name is ...");
	System.out.println(sb2);
	System.out.println(sb2.capacity());
	System.out.println(sb2.length());
	sb2.append("hello world , my name is ...");
	System.out.println(sb2);
	System.out.println(sb2.capacity());
	System.out.println(sb2.length());
}

输出结果:

20
0
hello world , my name is ...
42
28
hello world , my name is ...hello world , my name is ...
86
56

16
0
hello world , my name is ...
34
28
hello world , my name is ...hello world , my name is ...
70
56

可以看到动态扩容,StringBuffer(int capacity) 方法为20、42、86,StringBuffer()方法为16、34、70,可以看到StringBuffer的容量自动增加的时候是"2*旧的容量+2".,以此递增下去,建议使用默认构造方法StringBuffer()可以达到节省空间的目的。

  • 作者:阿澈师兄
  • 原文链接:https://blog.csdn.net/chengxu_ren_sheng/article/details/82967362
    更新时间:2022-07-11 13:48:42