Skip to content
Advertisement

Eclipse autogenerated toString() method

As par as I know concatinate String using + sign is not a good practice when you have large number of String. But when I check on eclipse generated toString() method (Write click on source file -> Source -> Generate toString() ) it has the same.

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 place to configure like my expected toString() method like bellow in eclipse or Why the eclipse doesn’t consider that.

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

I’m going to use auto generated toString() method to log my object values.

Kindly advice me.

Advertisement

Answer

No need to change anything, it’s compact and easily readable, javac will use StringBuilder for actual concatination, 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, like

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

+ or += is 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();
}

on each iteration a new StringBuilder is created and then converted to String. Here you should use StringBuilder explictily

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