scala - What's the correct way to convert from StringBuilder to String? - Stack Overflow
java - How to convert StringBuilder[] to String[] - Stack Overflow
In Java, why use StringBuilder instead of Strings?
What happens when i use toString() method on a StringBuilder?
The toString implementation currently just redirects to the result method anyway, so those two methods will behave in the same way. However, they express slightly different intent:
toStringrequests a textual representation ofStringBuilders current state that is "concise but informative (and) that is easy for a person to read". So, theoretically, the (vague) specification of this method does not forbid abbreviating the result, or enhancing conciseness and readability in any other way.resultrequests the actual constructed string. No different readings seem possible here.
Therefore, if you want to obtain the resulting string, use result to express your intent as clearly as possible.
In this way, the reader of your code won't have to wonder whether StringBuilder.toString might shorten something for the sake of "conciseness" when the string gets over 9000 kB long, or something like that.
The mkString is for something else entirely, it's mostly used for interspersing separators, as in "hello".mkString(",") == "h,e,l,l,o".
Some further links:
- The paragraph with "hashcode in hexadecimal" describes the default. It is just documentation inherited from
AnyRef, because the creator ofStringBuilderdidn't bother to provide more detailed documentation. - If you look into code, you'll see that
toStringis actually just delegating toresult. - The documentation of
StringBuilderalso mentionsresult()in the introductory overview paragraph.
Just use result().
TL;DR; use result as stated in the docs.
toString MUST never be called in anything at all for another purpose other than a quick debug.
mkString is inherited from collections hierarchy and it will basically create another StringBuilder so is very inefficient.
So far can't really tell the benefit of using it over Strings.
So let's say i have a code like this:-
StringBuilder str = new StringBuilder("hello");
System.out.println(str.toString()); So is it like there are two arrays, StringBuilder and String and we loop StringBuilder and copy it's contents character by character into the String? What would be the time complexity of this process?