1. 程式人生 > 其它 >java中string類concat方法和+的區別

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方法是最好的選擇