StringBuffer类的学习以及和String的区别

143 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第18天,点击查看活动详情

StringBuffer类

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

(2)很多方法与String相同,但StringBuffer是可变长度的

(3)StringBuffer是一个容器

public class StringBuffer01 {
    public static void main(String[] args) {

        //1. StringBuffer 的直接父类 是 AbstractStringBuilder
        //2. StringBuffer 实现了 Serializable, 即 StringBuffer 的对象可以串行化
        //3. 在父类中 AbstractStringBuilder 有属性 char[] value,不是 final
        // 该 value 数组存放 字符串内容,引出存放在堆中的
        //4. StringBuffer 是一个 final 类,不能被继承
        //5. 因为 StringBuffer 字符内容是存在 char[] value, 所有在变化(增加/删除)
        // 不用每次都更换地址(即不是每次创建新对象), 所以效率高于 String
        StringBuffer stringBuffer = new StringBuffer("hello");
    }
}

String 和 StringBuffer的区别

(1)String保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率

降低 //private final char value[];

(2)StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内

容,不用每次更新地址,效率较高 //char[] value;

String 和 StringBuffer 相互转换

public class StringAndStringBuffer {
    public static void main(String[] args) {
    
        //看 String——>StringBuffer
        String str = "hello tom";
        //方式 1 使用构造器
        //注意: 返回的才是 StringBuffer 对象,对 str 本身没有影响
        StringBuffer stringBuffer = new StringBuffer(str);
        
        //方式 2 使用的是 append 方法
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1 = stringBuffer1.append(str);
        
        //看看 StringBuffer ->String
        StringBuffer stringBuffer3 = new StringBuffer("周小末");
        //方式 1 使用 StringBuffer 提供的 toString 方法
        String s = stringBuffer3.toString();
        
        //方式 2: 使用构造器来搞定
        String s1 = new String(stringBuffer3);
    }
}

StringBuffer 类常见方法

public class StringBufferMethod {
    public static void main(String[] args) {
        StringBuffer s = new StringBuffer("hello");
        
        //增
        s.append(',');// "hello,"
        s.append("张三丰");//"hello,张三丰"
        s.append("赵敏").append(100).append(true).append(10.5);//"hello,张三丰赵敏 100true10.5" System.out.println(s);//"hello,张三丰赵敏 100true10.5"
        
        //删
        /*
        * 删除索引为>=start && <end 处的字符
        * 解读: 删除 11~14 的字符 [11, 14)
        */
        s.delete(11, 14);
        System.out.println(s);//"hello,张三丰赵敏 true10.5"
        
        //改
        //使用 周芷若 替换 索引 9-11 的字符 [9,11)
        s.replace(9, 11, "周芷若");
        System.out.println(s);//"hello,张三丰周芷若 true10.5"
        //查找指定的子串在字符串第一次出现的索引,如果找不到返回-1
        int indexOf = s.indexOf("张三丰");
        System.out.println(indexOf);//6
        
        //插
        //在索引为 9 的位置插入 "赵敏",原来索引为 9 的内容自动后移
        s.insert(9, "赵敏");
        System.out.println(s);//"hello,张三丰赵敏周芷若 true10.5"
        
        //长度
        System.out.println(s.length());//22
        System.out.println(s);
    }
}