Java基础 - String、StringBuilder、StringBuffer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010289802/article/details/81264444

简介

继承结构

String 解析

先看看 String 的源代码

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

    ......

    public String substring(int beginIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        int subLen = value.length - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
        return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
    }

}

从代码中可以看出:

1、String 类是 final 类,也即意味着 String 类不能被继承,并且它的成员方法都默认为 final 方法。在Java中,被final修饰的类是不允许被继承的,并且该类中的成员方法都默认为 final 方法。
2、String 类其实是通过 char 数组来保存字符串的。
3、无论是 substring、concat 还是其他 change 操作都不是在原有的字符串上进行的,而是重新生成了一个新的字符串对象。也就是说进行这些操作后,最原始的字符串并没有被改变。

区别

1、String 是字符串常量,是不可变的,进行修改操作会生成新的对象,而 StringBuilder 和 StringBuffer 是字符串变量,进行修改操作操作不会生成新的变量

2、StringBuilder 是非线程安全的(方法都用 synchronized 修饰),String 和 StingBuffer 是线程安全的。

3、在速度上,大部分情况下,StringBuilder > StringBuffer > String。但也有个特殊情况,如下:

String s = “a” + “b” + “c”;
StringBuffer Sb = new StringBuilder(“a”).append(“b”).append(“c”);

这种情况下 String 的速度是 比 StringBuilder 的速度快的。其实这是JVM的一个把戏,实际上:

String s = “a” + “b” + “c”  相当于 String s = "abc" ,所以不需要太多时间。

猜你喜欢

转载自blog.csdn.net/u010289802/article/details/81264444