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

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

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

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

句法:

public void trimToSize()

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

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

示例 1:

// Java program to demonstrate
// the trimToSize() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder("GeeksForGeeks");
  
        // add more string to StringBuilder
        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 StringBuilder object
        // with a String pass as parameter
        StringBuilder str
            = new StringBuilder();
  
        // add more string to StringBuilder
        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()