StringBuilder capacity()

前端 未结 8 1088
轮回少年
轮回少年 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:21

    From the API:

    Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

    Whenever you append something, there is a check to make sure that the updated StringBuilder won't exceed its capacity, and if it does, the internal storage of the StringBuilder is resized:

    int len = str.length();
    int newCount = count + len;
    if (newCount > value.length)
      expandCapacity(newCount);
    

    When data is added to it that exceeds its capacity it is re-sized according to the following formula:

    void expandCapacity(int minimumCapacity) {
    int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
        newCapacity = minimumCapacity;
    }
        value = Arrays.copyOf(value, newCapacity);
    }
    

    See the src.zip file that comes with the JDK for more information. (Above snippets taken from the 1.6 JDK)

提交回复
热议问题