StringBuilder capacity()

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

    Here's the logic: If you define a new instance of the StringBuilder class without a constructor, like so new StringBuilder(); the default capacity is 16. A constructor can be either an int or a String. For a String constructor, the default capacity is calculated like this

    int newCapacity = string.length() + 16;
    

    For an int constructor, the capacity is calculated like this

    int newCapacity = intSpecified + 16;
    

    If a new String is appended to the StringBuilder and the new length of the String is greater than the current capacity, then the capacity is calculated like this:

    int newCapacity = (oldCapacity + 1) * 2;
    

提交回复
热议问题