探秘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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值