StringBuffer的capacity
来源:互联网 发布:长江航运 知乎 编辑:程序博客网 时间:2024/05/10 01:20
二.用字符串初始化StringBuffer的内容
在声明一个StringBuffer变量的时候,用字符串进行初始化,容量会有变化么?
例2:
// 声明并初始化
StringBuffersb1 = 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());
// 利用append()来设置StringBuffer的内容
StringBuffersb11 = new StringBuffer();
sb11.append( " hello world " );
System.out.println( " withappend(), the capacity of StringBuffer is " + sb11.capacity());
System.out.println( " but the length of the StringBuffer is " + sb11.length());
StringBuffer
System.out.println(
System.out.println(
StringBuffer
sb11.append(
System.out.println( " with
System.out.println(
两者输出结果会一样么?
你一定认为,这不是显然的么。用长度为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
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}
3
4
结论:
StringBuffer的capacity等于用来初始化的字符串长度(11)加上StringBuffer的默认容量(16),而不是我们想当然的在默认容量16中拿出11个来存放字符串“hello world”。
如果我们不设置StringBuffer的capacity,分别对两者继续追加字符串,任其自动增长,其容量增长如下:
第一种情况:27,56,114,230,462,926...,
第二种情况:16,34,70
(为什么容量增加会是这种规律,后面会做解释)。
我想情况2节省空间的概率大一些,因为StringBuffer的capacity的增长比情况1慢,每次增加的空间小一些。
所以以后写代码的时候可以考虑使用第二种方法(使用StringBuffer的append()),特别是初始化字符串很长的情况。当然这会多写一行代码^+^:
0 0
- StringBuffer的Capacity详解
- StringBuffer的capacity
- StringBuffer的capacity()方法
- stringbuffer capacity()的疑问
- JAVA---揭秘StringBuffer的capacity
- 关于Java中StringBuffer的capacity问题
- StringBuffer的capacity如何让你的程序运行的更快(1)之续---揭秘StringBuffer的capacity
- StringBuffer中length()和capacity()的区别用法
- 在构造StringBuffer对象时,指定合适的capacity
- StringBuffer中length()和capacity()的区别用法
- StringBuffer setLength 和 append对capacity的影响
- StringBuffer中的length和capacity方法的区别
- Java-002-StringBuffer中的capacity的扩增机制
- java StringBuffer的length()和capacity()方法比较
- 关于StringBuffer对象的capacity方法返回值
- 如何让你的程序运行的更快(1)之续---揭秘StringBuffer的capacity
- 计算 WCDMA 的capacity
- vector的capacity增长方式
- 我的博客
- poj 3187 Backward Digit Sums(全排列变形)
- 一些navigator方法小结
- 蘑菇阵
- n皇后(递归回溯搜索)
- StringBuffer的capacity
- Android permission之android:protectionLevel
- vs2010编写局域网上位机
- 蓝桥杯 历届试题 城市建设
- 5-30 字符串的冒泡排序
- Spring MVC入门使用
- AIX系统新增用户并连接DB2数据库
- 一些Math方法小结
- 博弈(alpha-beta 剪枝)POJ —— 1085 Triangle War