package cn.itcast.stringbuilder.demo;
public class StringBuilderTest {
public static void main(String[] args) {
/*
* 将一个int数组变成字符串
*/
int[] arr = {1,2,3,4,5};
String s = arrayToString(arr);
System.out.println(s);
StringBuilder s1 = arrayToString_2(arr);
System.out.println(s1);
}
private static StringBuilder arrayToString_2(int[] arr) {//单线程StringBuilder效率高
StringBuilder sb = new StringBuilder();//不断把数组往StringBuilder里面装,最后一次性返回一整个容器
sb.append("[");
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
if (i!=arr.length-1) {
sb.append(",");
}
else {
sb.append("]");
}
}
return sb;
}
public static String arrayToString(int[] arr){//这是老方法,字符串连接的形式完成的
String str = "[";
for (int i = 0; i < arr.length; i++) {
if (i!=arr.length-1) {
str = str +arr[i]+",";//遍历一次,就在字符串常量池中new一个字符串,所以会产生N多字符串
}
else {
str = str + arr[i] + "]";
}
}
return str;
}
}
15-StringBuffer-13-常用对象API(StringBuilder类-练习)
最新推荐文章于 2020-10-01 22:00:27 发布