浅谈StringBuffer的capacity()方法

描述(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入门学习的一些细节。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦泽很努力耶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值