美文网首页
Java应懂的String、StringBuffer、Strin

Java应懂的String、StringBuffer、Strin

作者: 单线程的Cuke | 来源:发表于2020-04-17 17:33 被阅读0次

    String字符串常量

    public final class String
        implements java.io.Serializable, Comparable<String>, CharSequence{
        // private final char value[];
        private final int count;
    ...
    }
    

    StringBuffer 字符串变量(线程安全)

    public final class StringBuffer
        extends AbstractStringBuilder
        implements java.io.Serializable, CharSequence
    {
    ...
        public synchronized StringBuffer append(StringBuffer sb) {
            toStringCache = null;
            super.append(sb);
            return this;
        }
    
        /**
         * @since 1.8
         */
        @Override
        synchronized StringBuffer append(AbstractStringBuilder asb) {
            toStringCache = null;
            super.append(asb);
            return this;
        }
    ...
    }
    

    StringBuilder 字符串变量(线程不安全)

    public final class StringBuilder
        extends AbstractStringBuilder
        implements java.io.Serializable, CharSequence
    {
    ...
     public StringBuilder append(StringBuffer sb) {
            super.append(sb);
            return this;
        }
    
        @Override
        public StringBuilder append(CharSequence s) {
            super.append(s);
            return this;
        }
    ...
    }
    
    abstract class AbstractStringBuilder implements Appendable, CharSequence {
    ...
        /**
         * The value is used for character storage.
         */
        char[] value;
    
        /**
         * The count is the number of characters used.
         */
        int count;
    ...
    
    

    因为后两者继承AbstractStringBuilder ,所以其可变,而string 的count 是final的,所以是不可变的。
    关于线程安全,我们可以看到Stringbuffer 的方法都用synchronized 同步方法,这样保证线程安全,而Stringbuilder 则没有

    相关文章

      网友评论

          本文标题:Java应懂的String、StringBuffer、Strin

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