Java字符操作类StringBuffer与StringBuilder

当需要对字符串频繁进行修改操作时,建议使用StringBuffer或者StringBuilder类。因为操作过程中不会产生新的对象。

1)StringBuilder:不是线程安全的(不能同步访问),但有速度优势。一般情况下建议使用StringBuilder;

2)StringBuffer:线程安全,可同步访问。

package com.example.javatest;
/*
 *Author:W
 * 当需要对字符串进行频繁修改时,建议使用如下2个字符串类,因为操作时不产生新的未使用对象。
 * StringBuffer:线程安全
 * StringBuilder:不是线程安全的(不能同步访问),但有速度优势。一般情况下建议使用StringBuilder
 */
public class MainTest {

    public static void main(String[] args)
    {
        System.out.println("===StringBuilder===");
        StringBuilder sb = new StringBuilder(10);
        sb.append("I");
        sb.append(" am W,");
        sb.append("Please come in!");
        System.out.println("sb = "+sb);

        System.out.println("===StringBuffer===");
        StringBuffer  sb2 = new StringBuffer();
        sb2.append("Hello,");
        sb2.append("How old are you?");
        System.out.println("sb2 = "+sb2);
    }
}

运行结果如下:

 

おすすめ

転載: blog.csdn.net/hppyw/article/details/119596493