StringBuilder capacity()

前端 未结 8 1054
轮回少年
轮回少年 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)

    0 讨论(0)
  • 2020-12-01 15:25

    in Java 1.8

    public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }
    
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }
    

    for example :

    StringBuilder str = new StringBuilder();  
    System.out.println(str.capacity()); //16
    
    str.append("123456789012345"); 
    System.out.println(str.capacity()); //16
    
    str.append("12345678901234567890"); 
    System.out.println(str.capacity()); // 15 + 20 = 35
    
    0 讨论(0)
提交回复
热议问题