Java StringBuffer trimToSize() 方法



Java StringBuffer trimToSize() 方法用於調整 StringBuffer 物件字元序列的容量。簡而言之,它試圖減少字元序列使用的儲存空間。

在 Java 中,trim() 是一個內建方法,通常用於刪除或修剪給定序列或字串的空格

trimToSize() 不接受任何引數,該方法不丟擲任何異常。它不返回值。

語法

以下是Java StringBuffer trimToSize() 方法的語法:

public void trimToSize()

引數

  • 它不接受任何引數。

返回值

此方法不返回值。

示例:根據 StringBuffer 的容量修剪字串的大小

如果 StringBuffer 物件的值不為空,則 trimToSize() 方法會減小給定序列的容量。

在下面的示例中,我們使用值為“Hello World”的值例項化StringBuffer 類。 使用trimToSize() 方法,我們試圖減少 StringBuffer 物件的字元序列的容量。

public class TrimSize {
   public static void main(String[] args) {
      //create an object of the StringBuffer class
      StringBuffer sb = new StringBuffer("Hello World");
      System.out.println("StringBuffer: " + sb);
      //get the capacity and length
      System.out.println("The length of the sequence: " + sb.length());
      System.out.println("The sequence capacity before trim: " + sb.capacity());
      //using the trimToSize() method
      sb.trimToSize();
      System.out.println("The sequence capacity after trim: " + sb.capacity());
   }
}

輸出

執行上述程式後,將產生以下結果:

StringBuffer: Hello World
The length of the sequence: 11
The sequence capacity before trim: 27
The sequence capacity after trim: 11

示例:根據 StringBuffer 的容量修剪字串的大小

在下面的示例中,我們建立了一個值為“Tutorials Point”StringBuffer 類的物件。然後,使用append() 方法,我們將“India”值追加到它。使用trimToSize() 方法,我們試圖減小其容量。

public class StringBufferDemo {
   public static void main(String[] args) {
      //create an object of the StringBuffer class
      StringBuffer sb = new StringBuffer("Tutorials Point ");
      System.out.println("StringBuffer: " + sb);
      // append the string to StringBuffer
      sb.append("India");
      //By using trimToSize() method is to trim the sb object
      sb.trimToSize();
      System.out.println("After trim the object: " + sb);
   }
}

輸出

以下是上述程式的輸出:

StringBuffer: Tutorials Point 
After trim the object: Tutorials Point India
java_lang_stringbuffer.htm
廣告