https://www.sxt.cn/Java_jQuery_in_action/eight-buffebuild.html
StringBuffer和StringBuilder非常类似,均代表可变的字符序列。 这两个类都是抽象类AbstractStringBuilder的子类:
abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char[] value;
......
}
value数组没有用final修饰,所以它是可以修改的。
StringBuilder线程不安全,效率高,一般使用它。
StringBuffer线程安全,效率低。
public class Test {
public static void main(String[] args) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 26; i++) {
str.append((char)('a' + i));//append:往后追加,返回对这个对象本身
}
System.out.println(str);
str.reverse();//reverse:该字符序列被序列的相反代替,返回对这个对象本身
System.out.println(str);
str.setCharAt(2, '好');//设置指定索引处的字符,返回值是void
System.out.println(str);
str.insert(1, '我');//在指定索引处插入字符,返回对这个对象本身
System.out.println(str);
str.insert(0, '学').insert(6, '习').insert(7, '快').insert(10, '乐');
//链式调用。核心就是:该方法最后return this,把自己返回了。
System.out.println(str);
str.delete(20, 23);//删除区间,返回对这个对象本身
System.out.println(str);
}
}
输出结果:
abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba
zy好wvutsrqponmlkjihgfedcba
z我y好wvutsrqponmlkjihgfedcba
学z我y好w习快vu乐tsrqponmlkjihgfedcba
学z我y好w习快vu乐tsrqponmlhgfedcba
遇到循环累加字符串的时候,用String会生成很多对象,又占内存又耗时,可以用StringBuilder:
public class Test {
public static void main(String[] args) {
/**使用String进行字符串的拼接*/
String str8 = "";
//本质上使用StringBuilder拼接, 但是每次循环都会生成一个StringBuilder对象
long num1 = Runtime.getRuntime().freeMemory();//获取系统剩余内存空间
long time1 = System.currentTimeMillis();//获取系统的当前时间
for (int i = 0; i < 5000; i++) {
str8 = str8 + i;//相当于产生了10000个对象
}
long num2 = Runtime.getRuntime().freeMemory();
long time2 = System.currentTimeMillis();
System.out.println("String占用内存 : " + (num1 - num2));
System.out.println("String占用时间 : " + (time2 - time1));
/**使用StringBuilder进行字符串的拼接*/
StringBuilder sb1 = new StringBuilder("");
long num3 = Runtime.getRuntime().freeMemory();
long time3 = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
sb1.append(i);
}
long num4 = Runtime.getRuntime().freeMemory();
long time4 = System.currentTimeMillis();
System.out.println("StringBuilder占用内存 : " + (num3 - num4));
System.out.println("StringBuilder占用时间 : " + (time4 - time3));
}
}
输出结果:
String占用内存 : 49462968
String占用时间 : 52
StringBuilder占用内存 : 0
StringBuilder占用时间 : 1