StringBuilder capacity()

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

提交回复
热议问题