字符串拼接+和concat的區別


+和concat都可以用來拼接字符串,但在使用上有什么區別呢,先來看看這個例子。

public static void main(String[] args) {
    // example1
    String str1 = "s1";
    System.out.println(str1 + 100);//s1100
    System.out.println(100 + str1);//100s1

    String str2 = "s2";
    str2 = str2.concat("a").concat("bc");
    System.out.println(str2);//s2abc

    // example2
    String str3 = "s3";
    System.out.println(str3 + null);//s3null
    System.out.println(null + str3);//nulls3

    String str4 = null;
    System.out.println(str4.concat("a"));//NullPointerException
    System.out.println("a".concat(str4));//NullPointerException
}

concat源碼:

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);
}

所以可以得出以下結論:

  1. +可以是字符串或者數字及其他基本類型數據,而concat只能接收字符串。

  2. +左右可以為null,concat為會空指針。

  3. 如果拼接空字符串,concat會稍快,在速度上兩者可以忽略不計,如果拼接更多字符串建議用StringBuilder。

  4. 從字節碼來看+號編譯后就是使用了StringBuiler來拼接,所以一行+++的語句就會創建一個StringBuilder,多條+++語句就會創建多個,所以為什么建議用StringBuilder的原因。



作者:架構之路
鏈接:http://www.jianshu.com/p/f91499424cea
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM