在java中,String字符串拼接 concat方法 和字符串间直接用“+”号拼接的区别?
当我查看String类的concat函数的源码时,发现字符串连接是这么实现的: Java代码:
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
那么,字符串的连接符(+)的实现和这个有什么区别呢?如果有区别的话,那它是如何实现的呢?
此外,这两者分别在什么场合使用,有没有性能上的差异。
为了回答这个问题,我们可以做一个测试。
java代码:
public class Demo04StringGet {
public static void main(String[] args) {
//拼接字符串
String str1 = "Hello";
String str2 = "world";
String str3 = str1.concat(str2);
String str4 = str1+str2;
System.out.println(str3 == str4);
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
}
结果:
false
Hello
world
Helloworld
Helloworld
可以看出他们的地址并不相等
所以,+ 和 concat 肯定是有区别的。
因为在java中String是无法改变的所以,不管是用concat方法还是直接用+对字符串进行拼接,都会生成新对象。
此时我们再在代码中添加
public class Demo04StringGet {
public static void main(String[] args) {
//拼接字符串
String str1 = "Hello";
String str2 = "world";
String str3 = str1.concat(str2);
String str4 = str1+str2;
System.out.println(str3 == str4);
String str5 = "Helloworld";
System.out.println("==============");
System.out.println(str5 == str4);
System.out.println(str5 == str3);
System.out.println("==============");
System.out.println(str3);
System.out.println(str4);
}
}
结果如下:
false
==============
false
false
==============
Helloworld
Helloworld
发现都与str5不相等,说明不论是直接相加还是concat方法所得结果都不是直接调用字符串常量进程池中的结果
此时我们再添加几行
public class Demo04StringGet {
public static void main(String[] args) {
//拼接字符串
String str1 = "Hello";
String str2 = "world";
String str3 = str1.concat(str2);
String str4 = str1+str2;
String str6 = "Hello"+"world";
System.out.println(str3 == str4);
String str5 = "Helloworld";
System.out.println("==============");
System.out.println(str5 == str4);
System.out.println(str5 == str3);
System.out.println("==============");
System.out.println("==============");
System.out.println(str6 == str4);
System.out.println(str6 == str3);
System.out.println("==============");
System.out.println(str3);
System.out.println(str4);
}
}
结果如下
false
==============
false
false
==============
==============
false
false
==============
Helloworld
Helloworld
String c =a+b,它的实现过程其实是使用new StringBuilder()在堆中开辟了空间,最后调用to String方法转换为String对象,而"HelloWord"实际存储在常量池中,它们之间用==作对比(==是对引用地址值比较 )
通过查阅资料发现
concat和+
concat只能接收字符串,而+可以是字符串或者数字及其他基本类型数据。
+左右可以为null,concat会报空指针
如果拼接空字符串concat会稍快,但是可以忽略不计,如果拼接更多的字符串建议使用StringBuider。
+编译后就是使用了StringBuider来拼接,所以使用一行+就会创建一个StringBuilder,多个+就会创建多个,所以建议使用StringBuider。