Appending a StringBuilder to another StringBuilder
Asked Answered
M

2

9

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?

Millen answered 12/4, 2018 at 9:14 Comment(0)
I
23

StringBuilder has a public StringBuilder append(CharSequence s) method. StringBuilder implements the CharSequence interface, so you can pass a StringBuilder to that method.

Inbred answered 12/4, 2018 at 9:16 Comment(0)
S
3

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).

Systemic answered 12/4, 2018 at 9:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.