java中string类concat方法和+的区别
都可以将2个字符串拼接到一块,这一点2这功能相同。
以下代码的执行效果相同:
public class Document1 {
public static void main (String[] args){
String s1 = new String ("a");
String s2 = new String ("b");
String s3 = "c";
String s4 = "d";
System.out.printf("s1 + s2: %s\n",s1+s2);
System.out.printf("s1 concat s2: %s\n",s1.concat(s2));
System.out.printf("s3 + s4: %s\n",s3+s4);
System.out.printf("s3 concat s4: %s\n",s3.concat(s4));
System.out.printf("s1 + s3: %s\n",s1+s3);
System.out.printf("s1 concat s3: %s\n",s1.concat(s3));
}
}
但是 + 还可以将 字符串与非字符串(比如数字),拼接在一起,成为字符串。
要看看他们之间的区别,我们也可以从源码分析两者的区别,
concat是String方法,String重载了“+”操作符(提醒下:Java不支持其他操作符的重载)。
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);
}
源码中对String中+操作符的描述如下:
The Java language provides special support for the string concatenation operator ( + ),
and for conversion of other objects to strings.
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
简单的概括下:String本身是不变的对象,但是string的+号操作符是通过StringBuilder或StringBuffer(可以通过反汇编class文件,看到使用的StringBuilder来实现的。)
以上两个方法中都有开辟(new)以及销毁堆空间的操作,打大量的string操作导致效率很低。
所以在大量操作string字符串时,StringBuilder的append方法是最好的选择
欢迎一起来学习和指导,谢谢关注!
本文来自博客园,作者:xiexie0812,转载请注明原文链接:https://www.cnblogs.com/mask-xiexie/p/16081996.html