日常工作中,字符串的链接应该是比较常见的,小编研究了一下+和concat的差异
Demo
public static void main(String[] args) throws Exception {
String s1 = "hello";
String s2 = " peter";
System.out.println(s1 + s2);
System.out.println(s1.concat(s2));
System.out.println(s1+112);
System.out.println(s1.concat(1));//异常
}
Result
hello peter
hello peter
concat源码
/**
* Concatenates the specified string to the end of this string.
* <p>
* If the length of the argument string is {@code 0}, then this
* {@code String} object is returned. Otherwise, a
* {@code String} object is returned that represents a character
* sequence that is the concatenation of the character sequence
* represented by this {@code String} object and the character
* sequence represented by the argument string.<p>
* Examples:
* <blockquote><pre>
* "cares".concat("s") returns "caress"
* "to".concat("get").concat("her") returns "together"
* </pre></blockquote>
*
* @param str the {@code String} that is concatenated to the end
* of this {@code String}.
* @return a string that represents the concatenation of this object's
* characters followed by the string argument's characters.
*/
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);
}
差异结果
-
+可以是字符串或者数字及其他基本类型数据,而concat只能接收字符串。
-
+左右可以为null,concat为会空指针。
-
如果拼接空字符串,concat会稍快,在速度上两者可以忽略不计,如果拼接更多字符串建议用StringBuilder或StringBuffer 二者的区别参考StringBuffer和StringBuilder对比。
-
从字节码来看+号编译后就是使用了StringBuiler来拼接,所以一行+++的语句就会创建一个StringBuilder,多条+++语句就会创建多个,所以为什么建议用StringBuilder的原因。
1011

被折叠的 条评论
为什么被折叠?



