admin管理员组文章数量:1611546
一、构造方法
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()可以达到节省空间的目的。
本文标签: 区别方法StringBufferCapacitylength
版权声明:本文标题:StringBuffer类-构造方法和StringBuffer中length()和capacity()区别 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1728620846a1166339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论