String 与 StringBuilder 什么区别?StringBuilder扩充的底层原理

String 是不可变字符串,JDK源码定义String的时候其value是privite final char value[]

StringBuilder 是可变字符串,JDK源码在其父类定义的时候定义其value为 char[] value;

故String是不可变字符串,StringBuilder是可变字符串,从内存分析角度来看

若定义一个String的对象,若改变其值,则其指向的内存地址必定改变,

若定义一个StringBuilder对象,若改变其值,其内存地址未必一定改变,具体看如下两个案例。

其内存分析可见字符串生成个数分析

String b=new String("b");

for (int i=0;i<3;i++){

b+=i;

}

 

StringBuilder b=new StringBuilder("b");

        for (int i=0;i<3;i++){

            b.append(i);

        }

StringBuilder构造方法如下:

  /**
     * Constructs a string builder initialized to the contents of the
     * specified string. The initial capacity of the string builder is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

首先定义一个字符串长度+16的数组,

然后将str放到数组里面

后续调用 append 方法时首先检查其长度

 /**
     * Appends the string representation of the {@code int}
     * argument to this sequence.
     * <p>
     * The overall effect is exactly as if the argument were converted
     * to a string by the method {@link String#valueOf(int)},
     * and the characters of that string were then
     * {@link #append(String) appended} to this character sequence.
     *
     * @param   i   an {@code int}.
     * @return  a reference to this object.
     */
    public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                                     : Integer.stringSize(i);
        int spaceNeeded = count + appendedLength;
        ensureCapacityInternal(spaceNeeded);
        Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

若其所需长度与已有长度之和大于数组长度,

则调用Arrays.copyOf(value, newCapacity(minimumCapacity)),创建一个新数组,并将value的引用指向新数组

此时完成StringBuilder的扩充。

/**
     * For positive values of {@code minimumCapacity}, this method
     * behaves like {@code ensureCapacity}, however it is never
     * synchronized.
     * If {@code minimumCapacity} is non positive due to numeric
     * overflow, this method throws {@code OutOfMemoryError}.
     */
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }

 

新数组的长度为原数组的长度的二倍加2,即(value.length << 1) + 2

 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;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值