2012-12-30 120 views
4

就像我知道的那樣concatinate使用+符號的字符串在您有大量的String時不是一個好習慣。但是當我檢查生成的toString()方法(寫源點擊源文件 - >源 - >生成toString())它具有相同的。Eclipse自動生成toString()方法

public class Temp 
{ 
     private String tempName; 
     private String tempValue; 

     // here getters and setters 

    /* (non-Javadoc) 
     * @see java.lang.Object#toString() 
    */ 
@Override 
public String toString() { 
    return "Temp [tempName=" + tempName + ", tempValue=" + tempValue + "]"; 
} 

} 

有沒有配置像我預期的toString像日食波紋管或爲什麼日食不認爲()方法的任何地方。

public String expectedToString(){ 
    StringBuffer sb = new StringBuffer(); 
    sb.append("Temp [tempName=").append(tempName).append(",").append(" tempValue=").append(tempValue).append("]"); 
    return sb.toString(); 
} 

我打算使用自動生成的toString()方法來記錄我的對象值。

請告訴我。

+0

IIRC 1)現在最好的辦法是使用'StringBuilder'和2)時下編譯器改變了'字符串+''來表達StringBuilder'。有人可以確認嗎? – SJuan76

+2

使用+連接並不是一個真正的問題。編譯器優化+的使用,特別是涉及多個字符串時。 –

+1

非問題:在這種情況下,「+」和「.append()」和「.concat()」應該以相同的方式執行。有趣的鏈接:http://www.vogella.com/blog/2009/07/19/java-string-performanc/和[再次在字符串附加vs concat vs +](http://stackoverflow.com/questions/ 8962482 /又一次在字符串附加-vs-concat-vs) – paulsm4

回答

8

無需改變任何東西,它的結構緊湊,容易閱讀器javac將使用StringBuilder實際concatination,如果你反編譯你的Temp.class你會看到

public String toString() { 
    return (new StringBuilder("Temp [tempName=")).append(tempName).append(", tempValue=").append(tempValue).append("]").toString(); 
} 

但在其他情況下,如

String[] a = { "1", "2", "3" }; 
    String str = ""; 
    for (String s : a) { 
     str += s; 
    } 

++=是一個真正的性能殺手,看到反編譯的代碼

String str = ""; 
for(int i = 0; i < j; i++) { 
    String s = args1[i]; 
    str = (new StringBuilder(String.valueOf(str))).append(s).toString(); 
} 

在每次迭代中創建一個新的StringBuilder,然後轉換爲String。在這裏,你應該使用StringBuilder explictily

StringBuilder sb = new StringBuilder(); 
    for (String s : a) { 
     sb.append(s); 
    } 
    String str = sb.toString(); 
+0

謝謝我明白了。 – Suranga