StringBuffer与StringBuilder
StringBuilder和StringBuffer的对象是变量,对变量进行操作就是直接对该对象进行更改,而不进行创建和回收的操作,所以速度快很多。
StringBuilder相比较于StringBuffer,多线程使用时不安全,StringBuffer的方法有synchronized关键字进行修饰,多线程下安全。
public final class StringBuffer extends Object implements Serializable, CharSequence
public final class StringBuilder extends Object implements Serializable, CharSequence
两者构造方法与成员方法基本无差别
package com.qfedu.stringbuffer_stringbuilder;
public class Demo01 {
public static void main(String[] args) {
// Stringbuilder的无参构造会默认初始化容量为16
// public StringBuilder() {
// super(16);
// }
// StringBulider调用父类AbStractStringBuilder类的有参构造,并自动传入默认的初始化容量16
// public StringBuilder() {
// super(16);
// }
// AbstractStringBuilder的有参构造如上所示,参数为int类型,而此处的value即是StringBuilder类中用于存储字符的char数组:
// /**
// * The value is used for character storage.
// */
// char[] value;
StringBuilder stringBuilder = new StringBuilder();
System.out.println(stringBuilder.length());
System.out.println(stringBuilder.capacity());
// 传入字符串时,会进行拼接,将字符串拼接在初始化容量后面,并且这些字符被一个value数组进行了存放,value数组长度等于字符串长度
StringBuilder stringBuilder1 = new StringBuilder("你好,世界");
System.out.println(stringBuilder1.length());
System.out.println(stringBuilder1.capacity());
// 如果传入一个数字,执行方法与空参类似,此时初始化容量为输入的数字
// public StringBuilder(int capacity) {
// super(capacity);
// }
StringBuilder stringBuilder2 = new StringBuilder(15);
System.out.println(stringBuilder2.length());
System.out.println(stringBuilder2.capacity());
// 添加
System.out.println(stringBuilder.append("Hello"));
System.out.println(stringBuilder.append(2));
// 根据Unicode代码点进行赋值
System.out.println(stringBuilder.appendCodePoint(100));
// 返回当前容量
System.out.println(stringBuilder.capacity());
// 根据输入的索引 返回一个值
System.out.println(stringBuilder.charAt(2));
// 会根据指定索引返回对应的Unicode代码点的值
System.out.println(stringBuilder.codePointAt(0));
// 代替
System.out.println(stringBuilder1.replace(0,stringBuilder1.length(),"牛"));
// 逆序输出
System.out.println(stringBuilder.reverse());
// 输入新的长度,如果长度小于原字符串长度,就变成输入长度
stringBuilder2.append("12345678");
stringBuilder2.setLength(3);
System.out.println(stringBuilder2);
// 如果长度大于原来的长度。就用空格补齐
stringBuilder2.setLength(7);
System.out.println(stringBuilder2);
// 返回子序列
stringBuilder1.replace(0,stringBuilder1.length(),"你好世界321");
System.out.println(stringBuilder1.subSequence(0,stringBuilder1.length()));
System.out.println(stringBuilder1.substring(0,stringBuilder1.length()));
// 返回内容
System.out.println(stringBuilder1.toString());
}
}