哪位高手能给我解释一下这个Java程序的运行结果?
Java源程序如下:
import java.io.*;
public class capacity
{
public static void main(String[] args)
{
StringBuffer buffer = new StringBuffer( "Hello,how are you? ");
String output= "buffer= "+buffer.toString()+ "\nlength= "+buffer.length()+ "\ncapacity= "+buffer.capacity();
buffer.ensureCapacity(69);
output+= "\n\nNew capacity= "+buffer.capacity();
buffer.setLength(10);
output+= "\n\nNew length= "+buffer.length()+ "\nbuffer= "+buffer;
System.out.println(output);
}
}
程序运行结果如下:
buffer=Hello,how are you?
length=18
capacity=34
New capacity=70
New length=10
buffer=Hello,how
其中length=18,New length=10明白,capacity=34和New capacity=70是怎么算的?
请多多指教,谢谢!
------解决方案--------------------ensureCapacity
public void ensureCapacity(int minimumCapacity)Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:
The minimumCapacity argument.
Twice the old capacity, plus 2.
If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.
Parameters:
minimumCapacity - the minimum desired capacity.
--------------
larger of:
The minimumCapacity argument.
Twice the old capacity, plus 2. ///////
String output= "buffer= "+buffer.toString()+ "\nlength= "+buffer.length()+ "\ncapacity= "+buffer.capacity();
buffer.ensureCapacity(69);
output+= "\n\nNew capacity= "+buffer.capacity();
第一次capacity是34,通过ensureCapcity之后,34 <69,所以newCapcity=34*2+2=70
------解决方案--------------------length表示buffer中存放的当前字符串的长度,因为是how are you,18个字符,所以长度为18,但是StringBuffer作为一个可变长度的字符串容器,本身维持一个数据,就是,我当前的buffer能存放多少个字符而不需要进行增大存储量。
从程序结果看是34,
当你调用buffer.ensureCapacity(69);,是告诉buffer确保至少提供69个字符空间,至于打印的结果是70,这可能看一下StringBuffer的源代码就可以了。
结贴给分吧,谢谢。
------解决方案--------------------没有啊,我说的是不带参数的默认构造初始是 16,若初始化带了比如说是 3 个字符的字符串的话,那它的容量就是 3 + 16 = 19 了,以后扩展就变成了 (19 + 1)×2 = 40,再放不下就扩展为 (40 + 1)×2 = 82 了,以此类推……。
若当前容量 19 已经满,再 append 就会扩展至 40,但如果 append 的字符数超过 40 - 19 = 21 的话,这时的容量以当前字符的容量计算,下一次再在这个基础上进行扩展。
可以做一个测试:
StringBuffer sb = new StringBuffer( "abc ");
System.out.println(sb.capacity()); // 输出 19
sb.append( "aabadfasfasfsadfadffdadfsasdasd ");
System.out.println(sb.capacity()); // 输出 40
sb.append( "aabadfsssssssssddddddadfasdfadfasdfasdfasadfasfasd ");
// 输出 84(因为添加后总的字符数超过了 (40 + 1)×2 = 82 了,就以实际字符数计算)
System.out.println(sb.capacity());
sb.append( "aabadfssssssssssdfsdasdfsasdasdfsdasdfsasdasdfsasdasd ");
System.out.println(sb.capacity()); // 输出 170