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

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

Java中的 StringBuffer trimToSize() 方法及示例

StringBuffer 类trimToSize()方法是用于修剪 StringBuffer 对象的字符序列所使用的容量的内置方法。如果 StringBuffer 对象使用的缓冲区大于保存其当前字符序列所需的大小,则调用此方法来调整 StringBuffer 对象的大小,以将该对象转换为更节省空间的对象。调用此方法可能(但不是必须)影响后续调用 capacity() 方法返回的值。

句法:

public void trimToSize()

返回:此方法不返回任何内容。

下面的程序说明了 StringBuffer.trimToSize() 方法:

示例 1:

// Java program to demonstrate
// the trimToSize() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("GeeksForGeeks");
  
        // add more string to StringBuffer
        str.append("Contribute");
  
        // print capacity
        System.out.println("Capacity before "
                           + "applying trimToSize() = "
                           + str.capacity());
  
        // applying trimToSize() Method
        str.trimToSize();
  
        // print string
        System.out.println("String = " + str.toString());
  
        // print capacity
        System.out.println("Capacity after"
                           + " applying trimToSize() = "
                           + str.capacity());
    }
}
输出:
Capacity before applying trimToSize() = 29
String = GeeksForGeeksContribute
Capacity after applying trimToSize() = 23

示例 2:

// Java program to demonstrate
// the trimToSize() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer();
  
        // add more string to StringBuffer
        str.append("GeeksForGeeks classes");
  
        // print capacity
        System.out.println("Capacity before"
                           + " applying trimToSize() = "
                           + str.capacity());
  
        // applying trimToSize() Method
        str.trimToSize();
  
        // print string
        System.out.println("String = " + str.toString());
  
        // print capacity
        System.out.println("Capacity after "
                           + "applying trimToSize() = "
                           + str.capacity());
    }
}
输出:
Capacity before applying trimToSize() = 34
String = GeeksForGeeks classes
Capacity after applying trimToSize() = 21

参考:
https://docs.oracle.com/javase/10/docs/api/java Java()