StringBuilder capacity()

前端 未结 8 1069
轮回少年
轮回少年 2020-12-01 14:47

I noticed that the capacity method returns StringBuilder capacity without a logic way ... sometime its value is equals to the string length other t

8条回答
  •  温柔的废话
    2020-12-01 15:05

    When you append to the StringBuilder, the following logic happens:

    if (newCount > value.length) {
        expandCapacity(newCount);
    }
    

    where newCount is the number of characters needed, and value.length is the current size of the buffer.

    expandCapacity simply increases the size of the backing char[]

    The ensureCapacity() method is the public way to call expandCapacity(), and its docs say:

    Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:

    • The minimumCapacity argument.
    • Twice the old capacity, plus 2.

    If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

提交回复
热议问题