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/lang/StringBuffer.html#trimToSize()
极客教程