Roam
Roam

Reputation: 4949

Java -- StringBuilder using String & not StringBuilder

I'm using StringBuilder, instead of String, in my code in effort to make the code time-efficient during all that parsing & concatenation.

But when i look into its source, the substring() method of AbstractStringBuilder and thus StringBuilder is returning a String and not a StringBuilder.

What would be the idea behind this ?

Thanks.

Upvotes: 3

Views: 249

Answers (2)

NPE
NPE

Reputation: 500227

To go from one StringBuilder to another containing a segment of the original, you could use:

StringBuilder original = ...;
StringBuilder sub = new StringBuilder().append(original, offset, length);

This could have been provided as a method of original, but as things stand it isn't.

This aside, you should profile your code before engaging in micro-optimisations of this sort.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

The reason the substring method returns an immutable String is that once you get a part of the string inside your StringBuilder, it must make a copy. It cannot give you a mutable "live view" into the middle of StringBuilder's content, because otherwise you would run into conflicts of which changes to apply to what string.

Since a copy is to be made anyway, it might as well be immutable: you can easily make it mutable if you wish by constructing a StringBuilder around it, with full understanding that it is detached from the mutable original.

Upvotes: 6

Related Questions