美文网首页
2020-03-12-String的拼接

2020-03-12-String的拼接

作者: 耿望 | 来源:发表于2020-03-12 22:39 被阅读0次

    String

    在java中我们很喜欢用“+”来拼接两个字符串,但是实际上“+”拼接后是产生了一个新的String对象,它的实现原理是一个StringBuilder。比如下面的代码,两次的str其实是两个对象。

    String str = "a";
    str = str + "b";
    

    其实还有一种方法,就是使用String自己定义的concat方法。从源码上看,是将两个string进行了char数组的拼接,返回了一个新的String对象。

        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);
        }
        void getChars(char dst[], int dstBegin) {
            System.arraycopy(value, 0, dst, dstBegin, value.length);
        }
    

    另外,字符串拼接常用的两个类是StringBuilder和StringBuffer,他们都继承了AbstractStringBuilder。并且它们的append方法最终都是调用super方法实现的,但是我们可以看到StringBuffer是线程安全的,因为append方法是一个同步方法。

    StringBuilder

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

    StringBuffer

        @Override
        public synchronized StringBuffer append(String str) {
            toStringCache = null;
            super.append(str);
            return this;
        }
    

    最后,在它们的父类,append方法是一个char数组拼接的过程。

    AbstractStringBuilder

        public AbstractStringBuilder append(String str) {
            if (str == null)
                return appendNull();
            int len = str.length();
            ensureCapacityInternal(count + len);
            str.getChars(0, len, value, count);
            count += len;
            return this;
        }
    

    相关文章

      网友评论

          本文标题:2020-03-12-String的拼接

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