📜  Java中的 StringBuffer ensureCapacity() 方法及示例

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

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