描述(Description)
java.lang.StringBuffer.capacity()方法返回当前容量。 容量是新插入字符可用的存储量,超出该容量将进行分配。
声明(Declaration)
以下是java.lang.StringBuffer.capacity()方法的声明
public int capacity()
参数(Parameters)
Null
返回值(Return Value)
该方法返回当前容量
例子(Example)
public class CapacityTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();//默认容量为16
int originalLength = sb.length();
System.out.println("The initialization capacity is : " + sb.capacity());//初始容量即默认容量为16
int originalCapacity = sb.capacity();
sb.append("I am Jack.Nice to meet you!");//将指定的字符串追加到此字符序列
System.out.println("The string to be added : " + "I am Jack.Nice to meet you!" );
System.out.println("The length of the string to be added is : " + sb.length());//串长
int minimum_capacity = originalLength + sb.length();
System.out.println("The minimum capacity is : " + minimum_capacity);//最小容量 = 将要append(s)前的长度+ 将要append(s)中的s的串长
int proposedCapacityExpansion = (originalCapacity + 1) * 2;
System.out.println("New capacity to be expanded : " + proposedCapacityExpansion); //拟扩充的新容量 = (旧容量 + 1) * 2
if(minimum_capacity <= proposedCapacityExpansion)
{//如果最小容量不大于拟扩充的新容量,则以拟扩充的新容量进行扩充
System.out.println("The expansion of appended characters is expanded according to the new elements to be expanded");
}
else
{//如果最小容量大于拟扩充的新容量,则以最小容量进行扩充
System.out.println("The expansion of appended characters is expanded according to the minimum capacity of the proposed expansion");
}
}
}
原理(Principle)
拟扩充的新容量 = (旧容量 + 1) * 2 ,最小容量 = 将要append(s)前的长度+ 将要append(s)中的s的串长。如果拟扩充的新容量>=最小容量,则按照拟扩充的新容量进行扩充;否则按照最小容量进行扩充。
再见(Goodbye)
希望本文章能够对你有所帮助,如有错误请评论回复,我将及时改正,感谢阅读,创作不易,请关注点赞收藏,后续我将定时发布有关Java入门学习的一些细节。