StringBuffer类有两个属性分别为 length 和 capacity
请问这两个有什么区别啊? StringBuffer sb = new StringBuffer();
sb.append("java web");
System.out.println(sb.length());// 8
System.out.println(sb.capacity());// 这个是怎么不16呢?是和本身机器有关?
请问这两个有什么区别啊? StringBuffer sb = new StringBuffer();
sb.append("java web");
System.out.println(sb.length());// 8
System.out.println(sb.capacity());// 这个是怎么不16呢?是和本身机器有关?
每个字符串缓冲区都有一定的容量。只要字符串缓冲区所包含的字符序列的长度没有超出此容量,就无需分配新的内部缓冲区数组。如果内部缓冲区溢出,则此容量自动增大。StringBuffer
public StringBuffer(String str)构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容。该字符串的初始容量为 16 加上字符串参数的长度。
length是指已经放入char[]的字符个数
永远length<=capacity
16参考new StringBuffer()
经测试 输出的是16
length 指的是占用了多大空间
super(16);
}
length是指已经装了多少食物了。
Returns the current capacity.
The capacity is the amount of storage available for newly inserted characters,
beyond which an allocation will occur.
length 指的是占用了多大空间
sb.append("java web java web java web");
System.out.println(sb.length());//长度是26
System.out.println(sb.capacity());//输出是34
我想问那个capacity的增长是不是没规律的,只要length<capacity就行了~?
minimumCapacity 参数。
旧容量的两倍加 2。
/**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuffer() {
super(16);
}
看源码
要不你在new的时候给他分配个默认长度咯
java学习交流群:20378027。欢迎大家加入。