StringBuffer的解读(二)

本文深入探讨了StringBuffer在不同场景下的容量调整机制。从默认容量开始,逐步解析append操作如何影响StringBuffer的长度与容量,特别是在超出初始容量及扩容阈值时的行为变化。

StringBuffer的解读(二)

StringBuffer默认容量大小是16个字符。

  • StringBuffer后面append NULL的测试,代码如下:
public class Test {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("the");
        System.out.println("sb is: " + sb);;
        String str = null;
        sb.append(str);
        System.out.println("sb is: " + sb);;
    }
}
  • StringBuffer后面append字符串+原先字符数组<容量的测试,代码如下:
public class Test {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("the");
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
        sb.append(" redpig");
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
    }
}
  • StringBuffer后面append字符串+原先字符数组>容量,且<容量x2+2的测试,代码如下:
public class Test {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("the");
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
        sb.append(" redpig is writting java programs");
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
    }
}
  • StringBuffer后面append字符串+原先字符数组>容量x2+2的测试,代码如下:
public class Test {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("the");//original length is 3
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
        sb.append(" redpig is writting java programs for fun");//string's length is 33
        System.out.println("sb.length: " + sb.length());
        System.out.println("sb.capacity: " + sb.capacity());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值