Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 202
Roam Avatar asked Apr 27 '26 21:04

Roam


2 Answers

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.

like image 150
Sergey Kalinichenko Avatar answered Apr 30 '26 12:04

Sergey Kalinichenko


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.

like image 22
NPE Avatar answered Apr 30 '26 10:04

NPE