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


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



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuffer trimToSize() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。