當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。