Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a StringBuilder to another StringBuilder

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?

like image 841
Sam Avatar asked Apr 12 '18 09:04

Sam


2 Answers

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

like image 131
Eran Avatar answered Nov 19 '22 08:11

Eran


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

like image 3
Kayaman Avatar answered Nov 19 '22 09:11

Kayaman