import org.junit.Test; /* String是不可变的字符串序列,涉及到字符串的改变,会创建大量的对象 StringBuffer:是线程安全的,效率低,底层是采用char类型的数组存储数据,char数组默认长度是16 StringBuilder:是线程不安全的,效率高,底层是采用char类型的数组存储数据,char数组默认长度是16 共同点:他们的父亲都是AbstractStringBuilder抽象类 * */ public class Demo8 { @Test public void test1(){ String s =""; //StringBuffer sbf = new StringBuffer("从前有座山"); //StringBuffer sbf2 = sbf.append("1").append("2").append(3); StringBuilder sbf = new StringBuilder("从前有座山"); StringBuilder sbf2 = sbf.append("1").append("2").append(3); System.out.println("sbf2 = " + sbf2); int length=sbf2.length();//sbf2 = 从前有座山123 System.out.println("length = " + length);//length = 8 sbf2.setLength(10); System.out.println(sbf2);//从前有座山123 ;这有两个空格 int length2=sbf2.length(); System.out.println("length2 = " + length2);//length2 = 10 StringBuffer sbf3 = new StringBuffer("从前有座山山里有座庙"); //返回元素第一次出现的下标 int idx1=sbf3.indexOf("山"); System.out.println("idx1 = " + idx1);//idx1 = 4 //返回元素最后出现的下标 int idx2=sbf3.lastIndexOf("山"); System.out.println("idx2 = " + idx2);//idx2 = 5 //将指定元素添加到指定位置 sbf3.insert(6,"那边"); System.out.println(sbf3);//从前有座山山那边里有座庙 //删除指定元素[开始下标,结束下标) sbf3.delete(1,3); System.out.println(sbf3);//从座山山那边里有座庙 //删除指定位置的字符 sbf3.deleteCharAt(0); System.out.println(sbf3);//座山山那边里有座庙 //设置指定位置的字符 sbf3.setCharAt(0,'一'); System.out.println(sbf3);//一山山那边里有座庙 } }
代码2
package com.atguigu.day15; public class Demo9 { public static void main(String[] args) { testString(); testStringBuffer(); testStringBuilder(); } private static void testStringBuilder() { long start=System.currentTimeMillis(); StringBuilder sbd=new StringBuilder(""); for (int i = 0; i <10000 ; i++) { sbd.append(i); } long end =System.currentTimeMillis(); System.out.println("sbd用时:"+(end-start)); } private static void testStringBuffer() { long start=System.currentTimeMillis(); StringBuffer sbf=new StringBuffer(""); for (int i = 0; i <10000 ; i++) { sbf.append(i); } long end =System.currentTimeMillis(); System.out.println("sbf用时:"+(end-start)); } private static void testString() { long start=System.currentTimeMillis(); String s1=""; for (int i = 0; i <10000 ; i++) { s1+=i; } long end =System.currentTimeMillis(); System.out.println("s1用时:"+(end-start)); } }
输出
s1用时:774 sbf用时:2 sbd用时:1