简体   繁体   中英

How to use StringBuilder(int length) in Java

According to java doc, I got this idea:

StringBuilder(int length) in java ,creates an empty string Builder with the specified capacity as length.

I tried the code below:

StringBuilder sb = new StringBuilder(9);

But I can append length more than 9.

sb.append("123456789123456789123456789123456789123456789123456789");

What is the meaning of assign this length?

When you use StringBuilder repeatedly, it re-allocates its buffer each time that it needs to accommodate a longer string. If you know that your target string is going to be of a certain length, you can save on re-allocation by telling StringBuilder the length of your string.

This is going to be the length of the initial allocation; appending under this limit is not going to cause re-allocations. However, StringBuilder would not have a hard limit: going beyond the initial size is allowed.

The value that you passed in the constructor is the StringBuilder's initial capacity. Its not equal to the length of the string being built by it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM