Java StringBuffer ensureCapacity()方法及示例

Java StringBuffer ensureCapacity()方法及示例

StringBuffer类ensureCapacity() 方法确保其容量至少等于指定的minimumCapacity。

  • 如果StringBuffer的当前容量小于参数minimumCapacity,那么将分配一个新的内部数组,容量更大。
  • 如果minimumCapacity参数>旧容量的两倍,再加上2,那么新容量等于minimumCapacity,否则新容量等于旧容量的两倍,再加上2。
  • 如果作为参数传递的minimumCapacity参数<0,该方法不采取任何行动。

语法

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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程