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.
The toString() method can be used to convert a string object into a string.
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Use StringBuilder to generate toString output If you are using IDE like Eclipse, Netbeans, or IntelliJ then also using StringBuilder and append() method instead of + operator to generate toString method is a good way. By default both Eclipse and Netbeans generate toString method with concatenation operator.
A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With