当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuilder trimToSize() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。