I've written some code which has a lot of string creation. To try to avoid the expensive string creation over and over, I'm using the java StringBuilder
class.
My code is a bit like this:
public String createString(){
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < Integer.MAX_VALUE ; i++){ //its not actually this, but it's a large loop.
stringBuilder.append(appendString())
}
return stringBuilder.toString();
}
The appendString
method also instantiates a StringBuilder
and appends to it.
To save time, I noticed that I could make my appendString
method return a StringBuilder
, rather than a String
which avoids returning the stringBuilder using the .toString()
method like so:
public StringBuilder appendString(){
StringBuilder appendBuilder = new StringBuilder();
appendBuilder.append("whatever");
return appendBuilder;
}
This is all fine until I looked at the StringBuilder
documentation and realised that there is no append(StringBuilder stringBuilder)
method on the StringBuilder
class, only an append(String string)
.
So my question is, how does this code run? Is it casting StringBuilder
to String
anyway?
StringBuilder
has a public StringBuilder append(CharSequence s)
method. StringBuilder
implements the CharSequence
interface, so you can pass a StringBuilder
to that method.
There are plenty of append()
overloads, including append(CharSequence cs)
. Strings are handled in their own method, other CharSequences
not having their own overload are handled by the more general one.
Interestingly there is an append(StringBuffer sb)
.
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