在 Java 中為 StringBuffer 物件設定容量值


capacity() 方法返回當前容量。它是 StringBuffer 的一部分。它是為最近插入的字元存在的儲存量,此後會進行分配。

宣告 - capacity() 方法在 java.lang.StringBuffer 類中宣告,如下所示:-

public int capacity()

StringBuffer 物件的容量可以透過在例項化 StringBuffer 類時插入要設定的值來設定。

我們來看一個示例程式,展示如何設定容量值。

示例

 即時演示

import java.lang.*;
public class Example {
   public static void main(String[] args) {
      StringBuffer b = new StringBuffer(100);
      System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
      b = new StringBuffer(" ");
      // returns the current capacity of the String buffer which is 16 + 1
      System.out.println("Capacity for the StringBuffer Object = " + b.capacity());
   }
}

輸出

Capacity for the StringBuffer Object = 100
Capacity for the StringBuffer Object = 17

更新於: 2020 年 6 月 26 日

264 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.