package jichu12;
//String
public class Test2 {
public static void main(String[] args) {
/*String str="aaabbbb";
String str2=str.substring(2,5);
System.out.println(str);//aaabbbb
System.out.println(str2);//abb*/
//编译器做了优化,直接在编译的时候将字符进行拼接
String str1 = "hello"+"java";
String str2 = "hellojava";
System.out.println(str1==str2);//true
String str3="hello";
String str4 = "java";
//编译的时候不知大变量中存储的是什么,所以没办法在编译的时候优化
String str5=str3+str4;
System.out.println(str2==str5);//false
//做字符串比较的时候,使用equals 不要使用==
System.out.println(str2.equals(str5));//true
}
}
/
package jichu12;
public class TestStringBuilder {
public static void main(String[] args) {
//StringBuffer线程不安全,效率高(一般使用它);StringBuilder线程安全,效率高
StringBuffer sb=new StringBuffer("abcdefg");
System.out.println(Integer.toHexString(sb.hashCode()));//地址 16b4a017
System.out.println(sb);//abcdefg
sb.setCharAt(2,'M');
System.out.println(sb);//abMdefg
}
}
/
package jichu12;
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);//abcdefghijklmnopqrstuvwxyz
sb.reverse();//倒序
System.out.println(sb);//zyxwvutsrqponmlkjihgfedcba
sb.setCharAt(3,'猪');//把位置为3的换为猪
System.out.println(sb);//zyx猪vutsrqponmlkjihgfedcba
//在零的位置插入黄 链式调用,核心就是:该方法调用了return this,把自己返回了
sb.insert(0,'黄').insert(4,'大').insert(6,'仙');
System.out.println(sb);//黄zyx大猪仙vutsrqponmlkjihgfedcba
sb.delete(20,23);//删除20到23区间的字符,,也可以链式调用
System.out.println(sb);//黄zyx大猪仙vutsrqponmlkjfedcba
}
}
/
package jichu12;
//测试可变字符序列和不可变字符序列的陷阱
public class TestStringBuilder3 {
public static void main(String[] args) {
//使用String进行字符串的连接
String str="";
//本质上使用StringBuilder拼接,但是每次都会循环生成StringBuilder对象
long num1=Runtime.getRuntime().freeMemory();//获取系统剩余没存空间
long time1=System.currentTimeMillis();//获取系统当前时间
for (int i=0;i<5000;i++){
str=str+i;//相当于产生了10000个对象
}
long num2=Runtime.getRuntime().freeMemory();//获取系统剩余没存空间
long time2=System.currentTimeMillis();//获取系统当前时间
System.out.println("String占用内存:"+(num1-num2));//String占用内存:12017000
System.out.println("String占用时间:"+(time2-time1));//String占用时间:136
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("String占用内存:"+(num3-num4));//String占用内存:1999432
System.out.println("String占用时间:"+(time4-time3));//String占用时间:1
}
}