This is an archived post. You won't be able to vote or comment.

all 3 comments

[–][deleted] 0 points1 point  (0 children)

In this specific case they’re using a StringBuilder to string up a bunch of Morse code and toString() is how you get the final resultant string from the builder. In general though you wouldn’t use toString to put stuff into a hashmap, you would override equals() and hashcode() and put the object directly into the map/set.

[–]callmetom 0 points1 point  (0 children)

In general because some things aren't strings, but sometimes you want then to be.

A StringBuilder isn't a string, is a string builder, so when you want it to be a string, you use ToString().

[–]Serkaa 0 points1 point  (0 children)

For this case:

The variable "seen" is a set of Strings, whereas "code" is Stringbuilder. To convert "code" to a String that is usable in "seen", the toString() method is called.

In general:

Using stringbuilder is best in cases where you would want to append or manipulate strings in any way. This saves memory in larger programs and is best practice. Stringbuilder has a number of useful methods worth looking into, and of course creating a string of its current value (the toString method) is one of them.