Java.lang.StringBuffer.ensureCapacity() 方法
描述
java.lang.StringBuffer.ensureCapacity() 方法确保容量至少等于指定的最小值。 如果当前容量小于参数,则分配具有更大容量的新内部数组。 新容量是较大的 −
- minimumCapacity 参数。
- 旧容量的两倍,再加上 2。
如果 minimumCapacity 参数为非正数,则此方法不执行任何操作并简单地返回。
声明
以下是 java.lang.StringBuffer.ensureCapacity() 方法的声明。
public void ensureCapacity(int minimumCapacity)
参数
minimumCapacity − 这是所需的最小容量。
返回值
此方法不返回任何值。
异常
NA
示例
下面的例子展示了 java.lang.StringBuffer.ensureCapacity() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer buff1 = new StringBuffer("tuts point");
System.out.println("buffer1 = " + buff1);
// returns the current capacity of the string buffer 1
System.out.println("Old Capacity = " + buff1.capacity());
/* increases the capacity, as needed, to the specified amount in the
given string buffer object */
// returns twice the capacity plus 2
buff1.ensureCapacity(28);
System.out.println("New Capacity = " + buff1.capacity());
StringBuffer buff2 = new StringBuffer("compile online");
System.out.println("buffer2 = " + buff2);
// returns the current capacity of string buffer 2
System.out.println("Old Capacity = " + buff2.capacity());
/* returns the old capacity as the capacity ensured is less than
the old capacity */
buff2.ensureCapacity(29);
System.out.println("New Capacity = " + buff2.capacity());
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
buffer1 = tuts point Old Capacity = 26 New Capacity = 54 buffer2 = compile online Old Capacity = 30 New Capacity = 30

