String对象称为不可变对象,因为它里面有final修饰的char value[]数组,所以它是不可变字符序列
package cn.qq.com;
public class TestString {
public static void main(String[] args) {
// String str = "zxcv";
// String str1 = str.substring(2);
// String str2 = str.substring(2,3);
// System.out.println(str);
// System.out.println(str1);
// System.out.println(str2);
//编译器进行了优化,直接在编译的时候将字符串进行拼接
String str = "hello" + "world";
String str1 = "helloworld";
System.out.println(str == str1);//(true)
String str2 = "hello";
String str3 = "world";
//编译的时候不知道变量中存储的是什么,所以没办法在编译的时候进行优化
String str4 = str2 + str3;
System.out.println(str1 == str4);//(false)
}
}
StringBuilder线程不安全,效率高(一般使用它)它继承了AbstractStringBuilder,AbstractStringBuilder里面有char value[]数组,没有final修饰,所以它是可变字符序列
package cn.qq.com;
public class TestStringBuilder {
public static void main(String[] args) {
String str;
//StringBuilder线程不安全,效率高(一般使用StringBuilder)
//StringBuffer线程安全,效率低
StringBuilder sb = new StringBuilder("zxcvb");
System.out.println(Integer.toHexString(sb.hashCode()));
System.out.println(sb);
sb.setCharAt(3,'Y');
System.out.println(Integer.toHexString(sb.hashCode()));
System.out.println(sb);
}
}
StringBuilder/StringBuffer常用的一些方法
package cn.qq.com;
public class TestStringBuilder2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <26 ; i++) {
char tmp = (char)('a'+i);
sb.append(tmp);
}
System.out.println(sb);
sb.reverse();//逆序
System.out.println(sb);
sb.setCharAt(2,'于');//将该位置的字符代替
System.out.println(sb);
sb.insert(2,'洪');
System.out.println(sb);
//链式调用,核心就是:该方法调用了return this,把自己返回了
//insert和delete都调用了return this
sb.insert(2,'命').insert(2,'白');
System.out.println(sb);
//删除某一个区间段
sb.delete(2,26);
System.out.println(sb);
sb.delete(0,2).delete(0,2);
System.out.println(sb);
}
}
循环中使用StringBuilder中appen()方法
package cn.qq.com;
public class TestStringBuilder3 {
public static void main(String[] args) {
String str = "";
long num1 = Runtime.getRuntime().freeMemory();
long time1 = System.currentTimeMillis();
for (int i = 0; i <6000 ; i++) {
str = str + i;
}
long num2 = Runtime.getRuntime().freeMemory();
long time2 = System.currentTimeMillis();
System.out.println("String占用内存时间:"+(time2 - time1));
System.out.println("String占用内存空间:"+(num2 - num1));
StringBuilder sb = new StringBuilder("");
long num3 = Runtime.getRuntime().freeMemory();
long time3 = System.currentTimeMillis();
for (int i = 0; i <6000 ; i++) {
sb.append(i);
}
long num4 = Runtime.getRuntime().freeMemory();
long time4 = System.currentTimeMillis();
System.out.println("StringBuilder占用的内存时间:"+(time4 - time3));
System.out.println("StringBuilder占用的内存空间:"+(num4 - num3));
}
}