java.lang.StringBuilder.ensureCapacity()方法實例
java.lang.StringBuilder.ensureCapacity() 方法確保了容量至少等於指定的最小值。如果當前容量小於參數,那麼一個新的內部數組分配容量更大。新的容量較大:
- minimumCapacity參數。
- 舊容量的兩倍,再加上2。
如果 minimumCapacity 參數為非正數,則此方法不執行任何操作,隻是返回。
聲明
以下是java.lang.StringBuilder.ensureCapacity()方法的聲明
public void ensureCapacity(int minimumCapacity)
參數
-
minimumCapacity -- 這是最低所需容量。
返回值
This method does not return any value.
異常
-
NA
例子
下麵的例子顯示java.lang.StringBuilder.ensureCapacity()方法的使用。
package com.yiibai; import java.lang.*; public class StringBuilderDemo { public static void main(String[] args) { StringBuilder str1 = new StringBuilder("tuts point"); System.out.println("string1 = " + str1); // returns the current capacity of the string Builder 1 System.out.println("Old Capacity = " + str1.capacity()); /* increases the capacity, as needed, to the specified amount in the given StringBuilder object */ // returns twice the capacity plus 2 str1.ensureCapacity(28); System.out.println("New Capacity = " + str1.capacity()); StringBuilder str2 = new StringBuilder("compile online"); System.out.println("string2 = " + str2); // returns the current capacity of string Builder 2 System.out.println("Old Capacity = " + str2.capacity()); /* returns the old capacity as the capacity ensured is less than the old capacity */ str2.ensureCapacity(29); System.out.println("New Capacity = " + str2.capacity()); } }
讓我們來編譯和運行上麵的程序,這將產生以下結果:
string1 = tuts point Old Capacity = 26 New Capacity = 54 string2 = compile online Old Capacity = 30 New Capacity = 30