StringBuffer类的ensureCapacity()方法可确保容量至少等于指定的minimumCapacity。
- 如果当前容量为StringBuffer
- 如果minimumCapacity参数>旧容量的两倍加2,则新容量等于minimumCapacity,否则新容量等于旧容量的两倍加2。
- 如果minimumCapacity参数作为参数传递
用法:
public void ensureCapacity(int minimumCapacity)
参数:此方法采用一个参数minimumCapacity,它是最小所需容量。
返回值:此方法返回不返回任何内容。
下面的程序演示StringBuffer类的ensureCapacity()方法
示例1:
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
StringBuffer str = new StringBuffer();
// print string capacity
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(18);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
输出:
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 34
示例2:
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
StringBuffer
str
= new StringBuffer("Geeks For Geeks");
// print string capacity
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(42);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
输出:
Before ensureCapacity method capacity = 31 After ensureCapacity method capacity = 64
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#ensureCapacity(int)
相关用法
- Java ArrayList ensureCapacity()用法及代码示例
- Java StringBuffer codePointAt()用法及代码示例
- Java StringBuffer toString()用法及代码示例
- Java StringBuffer substring()用法及代码示例
- Java StringBuffer offsetByCodePoints()用法及代码示例
- Java StringBuffer trimToSize()用法及代码示例
- Java StringBuffer lastIndexOf()用法及代码示例
- Java StringBuffer getChars()用法及代码示例
- Java StringBuffer setCharAt()用法及代码示例
- Java StringBuffer codePointCount()用法及代码示例
- Java StringBuffer indexOf()用法及代码示例
- Java StringBuffer replace()用法及代码示例
- Java StringBuffer delete()用法及代码示例
- Java StringBuffer appendCodePoint()用法及代码示例
- Java StringBuffer deleteCharAt()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuffer ensureCapacity() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。