Java – StringBuilder using string instead of StringBuilder

I use StringBuilder instead of string in my code

But when I look at its source code, the substring () method abstractstringbuilder, so StringBuilder returns a string instead of StringBuilder

What's behind this?

thank you.

Solution

The reason why the substring method returns an immutable string is that once you get a part of the string in StringBuilder, it must be copied It can't give you a variable "real-time view" into the middle of the contents of StringBuilder, because otherwise you will encounter conflicts, and the changes apply to what string

Because you have to make a copy anyway, it may also be immutable: if you want to build a StringBuilder around it, you can easily make it variable and fully understand its separation from the variable original

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>