Java-StringBuffer类

StringBuffer类:

java.lang.StringBuffer代表可变的字符序列,可以对字符串内容进行增删

  • StringBuffer的直接父类是AbstractStringBuilder

  • StringBuffer实现了Serialiazable,即StringBuffer对象可以实现串行化

  • 再父类中, AbstractStringBuilder 有属性char[] value,但不是final类

  • 该value数组存放的是字符串的内容,因此不是存放在常量池中给,而是存放在堆中

  • StringBuffer是final类,不能被继承

  • 因为StringBuffer字符内容存储在char[] value,所以在变化的时候,可以直接更改内容,无需更换地址

    String和StringBuffer的区别

  • String保存的是字符串常量,因为String是final类,其中value[]数组是final类型,每次String更新实际上是更改地址,效率较低

  • StringBuffer保存的是字符串变量,里面的值可以更改,value[]数组不是final类型,因此value值指向堆,可以改变直接内容

    StringBuffer的三种构造器及其作用

源代码如下

/**
 * Constructs a string buffer with no characters in it and an
 * initial capacity of 16 characters.
 */
public StringBuffer() {
    super(16);//默认构造器会调用父类AbstractStringBuilder的构造器AbstractStringBuilder(int capacity)
    ,创建一个大小为16的char类型数组
}

/**
 * Constructs a string buffer with no characters in it and
 * the specified initial capacity.
 *
 * @param      capacity  the initial capacity.
 * @exception  NegativeArraySizeException  if the {@code capacity}
 *               argument is less than {@code 0}.
 */
public StringBuffer(int capacity) {
    super(capacity);//调用父类构造器,创建一个大小为capacity的char类型数组
}

/**
 * Constructs a string buffer initialized to the contents of the
 * specified string. The initial capacity of the string buffer is
 * {@code 16} plus the length of the string argument.
 *
 * @param   str   the initial contents of the buffer.
 */
public StringBuffer(String str) {
    super(str.length() + 16);//创建大小为str.length + 16的char类型数组
    append(str);//数组扩容并将str字符串追加到value数组尾部
}

StringBuffer和String类型转换

String s1 = "abc";
StringBuffer stringBuffer = new StringBuffer("abcd");

String -> StringBuffer

方式一:调用构造器
StringBuffer sb = new StringBuffer(s1);
方式二: 通过append方法
StringBuffer sb = new StringBuffer();
sb = sb.append(s1);

StringBuffer -> String

方式一:tostring方法
String s = stringBuffer.toString();
方式二:调用构造器
String s = new String(stringBuffer);

StringBuffer类的常用方法

增 append

删 delete

改 replace

查 indexOf

插 insert

获取长度 length

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值