📜  Java中的 StringBuilder capacity() 示例

📅  最后修改于: 2022-05-13 01:55:35.572000             🧑  作者: Mango

Java中的 StringBuilder capacity() 示例

StringBuilder 类capacity()方法用于返回 StringBUilder 对象的当前容量。容量是可用于插入新字符的存储量。
句法:

public int capacity()

返回值:该方法返回StringBuilder类的当前容量
下面的程序演示了 StringBuilder 类的 capacity() 方法:
示例 1:

Java
// 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("Default 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);
    }
}


Java
// 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);
    }
}


输出
Default Capacity of StringBuilder = 16
StringBuilder = Geek
Current Capacity of StringBuilder = 16

示例 2:

Java

// 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 Java()