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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。