该capacity()方法返回当前容量。它是StringBuffer的一部分。它是最近插入的字符存在的存储量,然后进行分配。
声明-该capacity()方法在java.lang.StringBuffer类中声明如下:
public int capacity()
可以通过在实例化StringBuffer类时插入要设置的值来设置StringBuffer对象的容量。
让我们看一个示例程序,该程序显示如何设置容量值。
import java.lang.*;
public class Example {
public static void main(String[] args) {
StringBuffer b = new StringBuffer(100);
System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
b = new StringBuffer(" ");
//返回字符串缓冲区的当前容量,该容量为16 +1-
System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
}
}输出结果
Capacity for the StringBuffer Object = 100 Capacity for the StringBuffer Object = 17