简体   繁体   English

Eclipse自动生成toString()方法

[英]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. 据我所知,当你有大量的String时,使用+符号的concatinate String不是一个好习惯。 But when I check on eclipse generated toString() method (Write click on source file -> Source -> Generate toString() ) it has the same. 但是当我检查eclipse生成的toString()方法时(写点击源文件 - > Source - > Generate 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 + "]";
}

}

Is there any place to configure like my expected toString() method like bellow in eclipse or Why the eclipse doesn't consider that. 是否有任何地方可以配置像我期望的toString()方法,如eclipse中的bellow或为什么eclipse不考虑这一点。

   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. 我将使用自动生成的toString()方法来记录我的对象值。

Kindly advice me. 请建议我。

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 无需更改任何内容,它紧凑且易于阅读,javac将使用StringBuilder进行实际连接,如果您反编译您的Temp.class,您将看到

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. 在每次迭代中,创建一个新的StringBuilder,然后转换为String。 Here you should use StringBuilder explictily 在这里你应该明确地使用StringBuilder

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM