StringBuilder:
StringBuilder常用的方法:
StringBuilder的使用:
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder("hello");
System.out.println(sb1);
sb.append("hello");
sb.append(true);
sb.append(12);
System.out.println(sb);
System.out.println(sb.reverse());
System.out.println(sb.length());
String sb2 = sb.toString();
System.out.println(sb2);
}
}
经典疑问:为啥操作字符串建议使用StringBuilder,而不用原来学过的String?
答:String频繁拼接字符串比较慢,而StringBuilder效率特别高,因为String每次赋值都会把原来的丢掉,看以下案例:
public class Test2 {
public static void main(String[] args) {
//掌握StringBulider的好处
//拼接100万次abc
//先用String测试下性能
String s = "";
for (int i = 0; i < 1000000; i++) {
//每次都把原来对象放弃掉,指向新的
s += "abc";
}
System.out.println(s);
//使用StringBuilder‘
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000000; i++) {
//每次都把原来对象放弃掉,指向新的
sb.append("abc");
}
System.out.println(sb);
}
}
StringBuffer:(与StringBuilder的区别)
SringBuilder案例练习:
public class Test3 {
public static void main(String[] args) {
System.out.println(getArray(new int[]{1, 2, 3, 4, 5}));
}
public static String getArray(int[] arr) {
if (arr == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
sb.append(arr[i]);
} else {
sb.append(arr[i]).append(",");
}
}
sb.append("]");
return sb.toString();
}
}