StringBuilder類的capacity()方法用於返回StringBUilder對象的當前容量。容量是可用於插入新字符的存儲量。
用法:
public int capacity()
返回值:此方法返回StringBuilder類的當前容量。
下麵的程序演示StringBuilder類的capacity()方法:
示例1:
// Java program to demonstrate
// the capacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object,
// default capacity will be 16
StringBuilder str = new StringBuilder();
// get default capacity
int capacity = str.capacity();
System.out.println("Deafult Capacity of StringBuilder = "
+ capacity);
// add the String to StringBuilder Object
str.append("Geek");
// get capacity
capacity = str.capacity();
// print the result
System.out.println("StringBuilder = " + str);
System.out.println("Current Capacity of StringBuilder = "
+ capacity);
}
}
輸出:
Deafult Capacity of StringBuilder = 16 StringBuilder = Geek Current Capacity of StringBuilder = 16
示例2:
// Java program to demonstrate
// the capacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
// with a String passed as parameter
StringBuilder
str
= new StringBuilder("WelcomeGeeks");
// get capacity
int capacity = str.capacity();
// print the result
System.out.println("StringBuilder = " + str);
System.out.println("Capacity of StringBuilder = "
+ capacity);
}
}
輸出:
StringBuilder = WelcomeGeeks Capacity of StringBuilder = 28
參考:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#capacity()
相關用法
- Java Buffer capacity()用法及代碼示例
- Java StringBuilder setCharAt()用法及代碼示例
- Java StringBuilder codePointCount()用法及代碼示例
- Java StringBuilder replace()用法及代碼示例
- Java StringBuilder reverse()用法及代碼示例
- Java StringBuilder codePointAt()用法及代碼示例
- Java StringBuilder setLength()用法及代碼示例
- Java StringBuilder Class用法及代碼示例
- Java StringBuilder codePointBefore()用法及代碼示例
- Java StringBuilder deleteCharAt()用法及代碼示例
- Java StringBuilder getChars()用法及代碼示例
- Java StringBuilder ensureCapacity()用法及代碼示例
- Java StringBuilder length()用法及代碼示例
- Java StringBuilder delete()用法及代碼示例
- Java StringBuilder subSequence()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder capacity() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。