Java中String和StringBuffer及StringBuilder 有什么区别

2022-07-14,,,,

前言:

string 是 java 语言非常基础和重要的类,提供了构造和管理字符串的各种基本逻辑。它是典型的 immutable 类,被声明成为 final class,所有属性也都是 final 的。也由于它的不可变性,类似拼接、裁剪字符串等动作,都会产生新的 string 对象。由于字符串操作的普遍性,所以相关操作的效率往往对应用性能有明显影响。 stringbuffer 是为解决上面提到拼接产生太多中间对象的问题而提供的一个类,我们可以用 append 或者 add 方法,把字符串添加到已有序列的末尾或者指定位置。stringbuffer 本质是一个线程安全的可修改字符序列,它保证了线程安全,也随之带来了额外的性能开销,所以除非有线程安全的需要,不然还是推荐使用它的后继者,也就是 stringbuilder。 stringbuilder 是 java 1.5 中新增的,在能力上和 stringbuffer 没有本质区别,但是它去掉了线程安全的部分,有效减小了开销,是绝大部分情况下进行字符串拼接的首选。

string类为什么是immutable(不可变的)

不可变类指的是对象一旦创建成功,就无法改变对象的值。jdk中很多类设计为不可变的integer,long和string等。相对应的改法中大多是可变类,创建成功后可以动态修改成员变量的属性值;

如何保证不可变

  • 类添加final修饰符,保证类是不可以被继承的;类继承会破坏类的不可变机制,只要覆盖父类的成员方法,并且在里面修改成员变量的值,那么所有子类以父类的形式出现的地方,类的属性都会被修改掉
  • 类成员属性设置为private,final的;这样可以保证成员属性是不可变的,但是仅仅这样还不够,因为如果成员变量是引用对象的话,可以改变引用对象的成员变量;通过第四点可以避免这一点;
  • 不提供修改成员变量的方法,比如setter;
  • 通过构造器构造对象,并进行深拷贝;如果是直接通过引用传入的对象直接赋值给成员,还是可以通过修改外部引用变量导致改变内部变量的值;

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;
    /**
     * class string is special cased within the serialization stream protocol.
     *
     * a string instance is written into an objectoutputstream according to
     * <a href="{@docroot}/../platform/serialization/spec/output.html" rel="external nofollow" >
     * object serialization specification, section 6.2, "stream elements"</a>
     */
    private static final objectstreamfield[] serialpersistentfields =
        new objectstreamfield[0];
    /**
     * initializes a newly created {@code string} object so that it represents
     * an empty character sequence.  note that use of this constructor is
     * unnecessary since strings are immutable.
     */
    public string() {
        this.value = "".value;
    }
    /**
     * initializes a newly created {@code string} object so that it represents
     * the same sequence of characters as the argument; in other words, the
     * newly created string is a copy of the argument string. unless an
     * explicit copy of {@code original} is needed, use of this constructor is
     * unnecessary since strings are immutable.
     *
     * @param  original
     *         a {@code string}
     */
    public string(string original) {
        this.value = original.value;
        this.hash = original.hash;
    }

    /**
     * allocates a new {@code string} so that it represents the sequence of
     * characters currently contained in the character array argument. the
     * contents of the character array are copied; subsequent modification of
     * the character array does not affect the newly created string.
     *
     * @param  value
     *         the initial value of the string
     */
    public string(char value[]) {
        this.value = arrays.copyof(value, value.length);
    }

通过源码可以看出来string是如何保证不可变的:

  • string类是finaly的,不允许继承
  • 成员变量value是private,final的
  • value没有setter方法
  • 构造方法,是通过克隆的方式来构造的
  • 返回value时,通过克隆的方式返回

string类为不可变对象的好处

字符串常量池的需要:

string aaa= "somestring"; string bbb = "somestring"; 这两个对象指向同一个内存,字符串常量池的好处是,在大量使用字符串的时候,可以节省内存,提供效率;如果string是可变对象,那么修改了一个,其他引用的地方全部发生变化了。

线程安全的考虑:

在并发场景下,多个线程同时读一个资源,不会引发竞争,但是同时写操作会引发竞争,string的不可变特点,所以线程安全的。

支持hash缓存:

因为字符串是不可变的,所以创建的时候hash被缓存下来了,不需要重新计算,使得字符串很适合做map的键,处理速度要快过其他的对象。

到此这篇关于java中string和stringbuffer及stringbuilder 有什么区别的文章就介绍到这了,更多相关java string 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java中String和StringBuffer及StringBuilder 有什么区别.doc》

下载本文的Word格式文档,以方便收藏与打印。