Java StringBuilder ensureCapacity()方法
java.lang.StringBuilder.ensureCapacity() 方法确保了容量至少等于指定的最小值。如果当前容量小于参数,那么一个新的内部数组分配容量更大。新的容量较大:
- minimumCapacity参数。
- 旧容量的两倍,再加上2。
如果 minimumCapacity 参数为非正数,则此方法不执行任何操作,只是返回。
1 语法
public void ensureCapacity(int minimumCapacity)
2 参数
minimumCapacity : 这是最低所需容量。
3 返回值
此方法不返回任何值。
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java StringBuilder ensureCapacity()方法
*/
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
热门文章
优秀文章