美文网首页
Java中String的concat方法分析

Java中String的concat方法分析

作者: BestbpF | 来源:发表于2018-07-08 12:37 被阅读42次

    1、源码展示

        public String concat(String str) {
            int otherLen = str.length();
            if (otherLen == 0) {
                return this;
            }
            int len = value.length;
            char buf[] = Arrays.copyOf(value, len + otherLen);
            str.getChars(buf, len);
            return new String(buf, true);
        }
    

    2、源码分析

    • value为String内部维护的一个字符数组,用来存储String的值
    • 首先判断需要拼接的字符串是否长度为0,若为0则返回预原字符串
    • 使用Arrays.copyOf方法将value复制到buf,且buf长度扩充为原字符串和新字符串长度之和
    • 使用String的getChars方法将str的字符全部复制到buf索引len(即原字符串之后),完成拼接
    • 返回新的字符串

    相关文章

      网友评论

          本文标题:Java中String的concat方法分析

          本文链接:https://www.haomeiwen.com/subject/iohouftx.html