首页 新闻 会员 周边 捐助

StringBuilder初始容量和扩容规则

0
悬赏园豆:10 [待解决问题] 浏览: 72次

StringBuilder如果不指定初始容量,默认容量大小是多少,扩容是每次容量大小*2吗?

j_s_z的主页 j_s_z | 初学一级 | 园豆:186
提问于:2025-01-19 17:11
< > 人人可用的开源BI工具
分享
所有回答(2)
0

    /**
     * Returns a capacity at least as large as the given minimum capacity.
     * Returns the current capacity increased by the same amount + 2 if
     * that suffices.
     * Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
     * unless the given minimum capacity is greater than that.
     *
     * @param  minCapacity the desired minimum capacity
     * @throws OutOfMemoryError if minCapacity is less than zero or
     *         greater than Integer.MAX_VALUE
     */
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int newCapacity = (value.length << 1) + 2;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }

左移一位,然后 + 2,相当于*2 再 +2,我这是Java8

echo_lovely | 园豆:1584 (小虾三级) | 2025-01-20 08:18
    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity of 16 characters.
     */
    public StringBuilder() {
        super(16);
    }

    /**
     * Constructs a string builder with no characters in it and an
     * initial capacity specified by the {@code capacity} argument.
     *
     * @param      capacity  the initial capacity.
     * @throws     NegativeArraySizeException  if the {@code capacity}
     *               argument is less than {@code 0}.
     */
    public StringBuilder(int capacity) {
        super(capacity);
    }

不给的话默认容量是16

支持(0) 反对(0) echo_lovely | 园豆:1584 (小虾三级) | 2025-01-20 08:21
0

StringBuilder 的初始容量和扩容规则在 Java 中有一些特定的定义:

初始容量

  • 如果在创建 StringBuilder 对象时不指定初始容量,则默认为 16 个字符。这意味着,如果你使用 new StringBuilder(),它的初始容量就是 16 字符。

扩容规则

  • StringBuilder 中的内容超过当前容量时,它会进行扩容。扩容的规则是将当前容量加倍,这实际上是 当前容量 * 2
  • 例如,如果当前容量是 16,当需要扩容时,新的容量将变为 32。如果再一次超过这个容量,新的容量将变为 64,以此类推。

总结

  • 默认初始容量:16
  • 扩容方式:当前容量 * 2

这种设计使得 StringBuilder 在字符串连接和修改时能够高效地管理内存,避免频繁的内存分配。如果你知道将要使用的字符串的最大长度,可以在创建 StringBuilder 时指定一个合适的初始容量,以提高性能。

Technologyforgood | 园豆:7840 (大侠五级) | 2025-01-20 09:10
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册
Top