Eclipse auto-generates toString () method

As far as I know, concatinate String using the + sign is not good practice when you have a large number of String. But when I check the eclipse generated method toString () (write a click on the source file β†’ Source β†’ Generate toString ()), it has the same thing.

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 + "]"; } } 

Is there any room for customization, for example, my expected toString () method, similar to the one below in eclipse, or Why eclipse does not consider this.

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

I am going to use the automatically generated toString () method to register the values ​​of my objects.

I ask for advice.

+4
source share
1 answer

No need to change anything, compact and easy to read, javac will use StringBuilder to actually concatenate, if you decompile your Temp.class, you will see

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

But in other situations, such as

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

+ or += - a real performance killer, see decompiled code

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

at each iteration, a new StringBuilder is created and then converted to String. Here you should use StringBuilder explicitly

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

All Articles