StringBuilder类的suresureCapacity(int minimumCapacity)方法可帮助我们确保容量至少等于作为参数传递给方法的指定minimumCapacity。
- 如果StringBuilder的当前容量小于参数minimumCapacity,则将分配一个具有更大容量的新内部数组。
- 如果minimumCapacity参数大于旧容量的两倍加2,则新容量等于MinimumCapacity,否则新容量等于旧容量的两倍加2。
- 如果作为参数传递的minimumCapacity参数为not-positive,则此方法不执行任何操作。
用法:
public void ensureCapacity(int minimumCapacity)
参数:此方法接受一个参数minimumCapacity,它表示所需的最小所需容量。
返回值:此方法不返回任何内容。
下面的程序演示StringBuilder类的ensureCapacity()方法:
示例1:
在此程序中,等于18的minimumCapacity自变量小于旧容量的两倍,加上等于34的2则新容量等于34。
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
System.out.println("Before ensureCapacity "
+ "method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(18);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
输出:
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 34
示例2:
在此程序中,等于44的minimumCapacity参数大于旧容量的两倍,再加上等于34的2,则新容量等于34。
// Java program to demonstrate
// the ensureCapacity() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
StringBuilder str = new StringBuilder();
// print string capacity
System.out.println("Before ensureCapacity"
+ " method capacity = "
+ str.capacity());
// apply ensureCapacity()
str.ensureCapacity(44);
// print string capacity
System.out.println("After ensureCapacity"
+ " method capacity = "
+ str.capacity());
}
}
输出:
Before ensureCapacity method capacity = 16 After ensureCapacity method capacity = 44
参考:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#ensureCapacity(int)
相关用法
- Java StringBuffer ensureCapacity()用法及代码示例
- Java ArrayList ensureCapacity()用法及代码示例
- Java StringBuilder capacity()用法及代码示例
- Java StringBuilder codePointBefore()用法及代码示例
- Java StringBuilder subSequence()用法及代码示例
- Java StringBuilder codePointAt()用法及代码示例
- Java StringBuilder setLength()用法及代码示例
- Java StringBuilder delete()用法及代码示例
- Java StringBuilder charAt()用法及代码示例
- Java StringBuilder reverse()用法及代码示例
- Java StringBuilder setCharAt()用法及代码示例
- Java StringBuilder replace()用法及代码示例
- Java StringBuilder getChars()用法及代码示例
- Java StringBuilder codePointCount()用法及代码示例
- Java StringBuilder Class用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuilder ensureCapacity() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。