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