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
广告
© . All rights reserved.