StringBuilder类sureCapacity()方法 (StringBuilder Class ensureCapacity() method)
ensureCapacity() method is available in java.lang package.
sureCapacity()方法在java.lang包中可用。
ensureCapacity() method is used to check the ensurity of the capacity with the given capacity (i.e. we ensure that the capacity is equal to the given argument).
guaranteeCapacity()方法用于检查具有给定容量的容量的安全性(即,我们确保容量等于给定参数)。
In this method let suppose argument capacity > current capacity so in that case new space allocated for an array with larger capacity so the new capacity will be:
在此方法中,假设参数容量>当前容量,因此在这种情况下,为具有较大容量的数组分配了新空间,因此新容量将为:
Note: When we pass the negative value as an argument so in that case no action will perform and simply returns 注意:当我们将负值作为参数传递时,在这种情况下,将不会执行任何操作,只会返回New Capacity = New Capacity > min_cap New Capacity = 2*old Capacity +2
ensureCapacity() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
guaranteeCapacity()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
ensureCapacity() method does not throw an exception at the time of the ensurity of the capacity.
sureCapacity()方法在确保容量时不会引发异常。
Syntax:
句法:
public void ensureCapacity(int min_cap);
Parameter(s):
参数:
int min_cap – represents the minimum capacity required to perform action.
int min_cap –表示执行操作所需的最小容量。
Return value:
返回值:
The return type of this method is void, it returns nothing.
此方法的返回类型为void ,不返回任何内容。
Example:
例:
// Java program to demonstrate the example
// of void ensureCapacity(int min_cap)
// method of StringBuilder
public class EnsureCapacity {
public static void main(String[] args) {
// Creating an StringBuilder object
StringBuilder st_b = new StringBuilder("Java World");
// Display st_b
System.out.println("st_b = " + st_b);
// Display Current Capacity st_b i.e. 16+10
System.out.println("st_b.capacity() = " + st_b.capacity());
// By using ensureCapacity() method is to extend the capacity
// with the given amount to st_b object if required
// it returns twice the old capacity + 2 i.e.(2*st_b+2)
st_b.ensureCapacity(54);
// Display Current Capacity st_b i.e.54
System.out.println("st_b.ensureCapacity(54) = " + st_b.capacity());
}
}
Output
输出量
st_b = Java World
st_b.capacity() = 26
st_b.ensureCapacity(54) = 54
翻译自: https://www.includehelp.com/java/stringbuilder-ensurecapacity-method-with-example.aspx