字符串拼接的办法
+号拼接
String a="hello";
String b="world";
String c=a+" "+b;
System.out.println(c) //hello world
实际原理:
对文件进行反编译 javap -c name.class 得到下面
可以发现+号的底层实现原理其实类似于下面
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
System.out.println(sb.toString());
concat方法
String a="hello";
a.concat(" world");
String b=a.concat(" world");
System.out.println(a); //hello
System.out.println(b); //hello world
可以发现concat并不是改变原字符串,对于String的改变都是创建了一个新的String对象。
实现原理:
1.可以发现是创建一个新的字符数组
2.将两个字符串复制到字符数组当中去。
3.通过new String 的方式将字符数组转为String返回
StringBuffer (线程安全)
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
System.out.println(sb.toString());
StringBuilder(线程不安全)
StringBuffer sb = new StringBuffer();
sb.append(a);
sb.append(b);
System.out.println(sb.toString());
一点建议
- 循环体内的字符串拼接,使用StringBuilder的append方法。因为+号拼接,每一次都会new出一个StringBuilder,造成资源浪费。效率降低
- 在并发编程下,将StringBuilder换成StringBuffer