Java StringBuilder trimToSize()方法及示例

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/lang/StringBuilder.html#trimToSize()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程