字符串append方法的源码流程

今天看到字符串的append方法返回的新对象不改变内存地址,特意看了看源码
首先是测试代码

public class stringbufferapp {
    public static void main(String[] args){

        StringBuilder str = new StringBuilder("abcde");             //默认分配(总长+16)的大小
        System.out.println(str.hashCode());

        str.append("abcjioasjdioajfakljg;lkag");
        System.out.println(str.hashCode());
    }
}

输出结果:
460141958
460141958


进入StringBuilder类的append方法:

@Override
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }

进入父类AbstractStringBuilder的append方法:

public AbstractStringBuilder append(String str) {   //传入添加的append的字符串
        if (str == null)                                                  //字符串的判断
            return appendNull();
        int len = str.length();                                       //append的字符串长度
        ensureCapacityInternal(count + len);             //@1    调用方法判断长度是否超了  count+len=总长
        str.getChars(0, len, value, count);                   //@2    
        count += len;                                                 //count=新字符串长度
        return this;
    }

@1

private void ensureCapacityInternal(int minimumCapacity) {
        if (minimumCapacity - value.length > 0) {                                       //判断是否超过当前长度
            value = Arrays.copyOf(value,newCapacity(minimumCapacity)); //复制当前数组到新value数组中,newCapacity()返回新长度,
        }
    }

@2
getChar()方法调用了
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);函数,
**

//源头找到了,下面为该方法的注释,规定了返回相同的HASHCODE,所以返回的地址相同,系统方法,看不到函数体

**

  • Returns the same hash code for the given object as
    • would be returned by the default method hashCode(),
    • whether or not the given object’s class overrides
    • hashCode().
    • The hash code for the null reference is zero.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值