探秘Java中String、StringBuilder以及StringBuffer的区别

package com.company;

public class string1 {
    public static void main(String[] args) {
        System.out.println("===============string========================");
        //string类具体有不可变性,因为String类是由final修饰的,所以是不可变的
        String str ="hello";
        System.out.println(str.hashCode ());
        //可以看到,在没有new新的String时,对原来的字符进行修改,String的hashCode值会改变。
        // 程序运行时会额外创建一个对象,保存 "helloworld"。当频繁操作字符串时,就会额外产生很多临时变量。
        str=str+"world";//helloworld
        System.out.println(str);//hello
        System.out.println(str.hashCode ());

        System.out.println("===============StringBuilder==================");
        // 创建一个StringBuilder对象,用来存储字符串
        StringBuilder hobby=new StringBuilder("爱慕课");
        System.out.println(hobby);
        System.out.println(hobby.hashCode ());
        //StringBuild的hashCode值不变。
      //  由上我们可以看出,String类具有不可变性,其字符串发生改变后会创建新的位置来存储;而StringBuild和StringBuffer是在原有对象上进行修改,其位置不变.
        hobby=hobby.append ("123");
        System.out.println(hobby);
        System.out.println(hobby.hashCode ());

        System.out.println("===============StringBuffer==================");
// StringBuffer ,用来存储字符串
        StringBuffer hello=new StringBuffer ("love慕课");
        System.out.println(hello);
        System.out.println(hello.hashCode ());
        //StringBufferStringBuffer 是线程安全的,而 StringBuilder 则没有实现线程安全功能,所以性能略高。因此一般情况下,如果需要创建一个内容可变的字符串对象,应优先考虑使用 StringBuilder 类。
        hello=hello.append ("123");
        System.out.println(hello);
        System.out.println(hello.hashCode ());
    }
}

运行结果:

===============string========================
99162322
helloworld
-1524582912
===============StringBuilder==================
爱慕课
460141958
爱慕课123
460141958
===============StringBuffer==================
love慕课
1163157884
love慕课123
1163157884
 

更多请参考:http://www.cnblogs.com/dolphin0520/p/3778589.html

https://my.oschina.net/u/3877294/blog/2250728

猜你喜欢

转载自blog.csdn.net/qwert789p/article/details/89136068