StringBuilder和StringBuffer可变字符序列

StringBuilder线程不安全,效率高,StringBuffer线程安全,效率低

public class TestStringBuilder {

    public static void main(String[] args) {
        String str;
        //StringBuilder线程不安全,效率高,StringBuffer线程安全,效率低
        StringBuilder sb=new StringBuilder("abcdefg");
        System.out.println(Integer.toHexString(sb.hashCode()));//地址 
        System.out.println(sb);
        sb.setCharAt(2,'M');//把c换成M
        System.out.println(Integer.toHexString(sb.hashCode()));
        System.out.println(sb);
    }

}
package 常用类;

public class TestStringBuilder2 {

    public static void main(String[] args) {
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<26;i++){
            char temp=(char)('a'+i);
            sb.append(temp);//拓展
        }

        System.out.println(sb);
        sb.reverse();//倒序
        System.out.println(sb);
        sb.setCharAt(3, '你');//替换
        System.out.println(sb);
        sb.insert(5, '哈').insert(9, '呢');//链式调用,核心:该方法调用了return this,把自己放回了
        System.out.println(sb);
        sb.delete(20, 23);
        System.out.println(sb);
    }

}


输出:
abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba
zyx你vutsrqponmlkjihgfedcba
zyx你v哈uts呢rqponmlkjihgfedcba
zyx你v哈uts呢rqponmlkjiedcba

package 常用类;
//测试可变字符序列和不可变字符序列使用的陷阱
public class StringBuilder3 {

    public static void main(String[] args) {
        //String进行字符串拼接
        String str="";
        long num1=Runtime.getRuntime().freeMemory();//获取系统剩余内存
        long time1=System.currentTimeMillis();//获取系统当前时间
        for(int i=0;i<500;i++){
            str=str+i;                    //产生一万个对象,非常不推荐!
        }
        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<500;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占用内存1018528
String占用时间2
StringBuilder占用内存0
StringBuilder占用时间0

你可能感兴趣的:(StringBuilder和StringBuffer可变字符序列)