面试题----String s = "Hello";s = s + " world!";这两行代码执行后,原始的 String 对象 中的内容到底变了没有?

这题的答案是: 

没有。因为 String 被设计成不可变(immutable)类,所以它的所有对象都是不可变对象。在这段代码中,s 原先指向一个 String 对象,内容是 "Hello",然后我们对 s 进行了“+”操作,那么 s 所指向的那个对象是否发生了改变呢?答案是没有。这时,s 不指向原来那个对象了,而指向了另一个 String 对象,内容为"Hello world!",原来那个对象还存在于内存之中,只是 s 这个引用变量不再指向它了。

随着问题的深入就会发现,在项目中应该尽可能的使用String。多使用StringBuffer。

所以在这对String StringBuffer和StringBuilder进行了比较:

  1. 首先说运行速度,或者说是执行速度,在这方面运行速度快慢为:StringBuilder > StringBuffer > String

  String最慢的原因:

  String为字符串常量,而StringBuilder和StringBuffer均为字符串变量,即String对象一旦创建之后该对象是不可更改的,但后两者的对象是变量,是可以更改的。

  这里说的也是上面这道面试题的答案。

  2. 再来说线程安全

  在线程安全上,StringBuilder是线程不安全的,而StringBuffer是线程安全的

  如果一个StringBuffer对象在字符串缓冲区被多个线程使用时,StringBuffer中很多方法可以带有synchronized关键字,所以可以保证线程是安全的,但StringBuilder的方法则没有该关键字,所以不能保证线程安全,有可能会出现一些错误的操作。所以如果要进行的操作是多线程的,那么就要使用StringBuffer,但是在单线程的情况下,还是建议使用速度比较快的StringBuilder。

  3. 总结一下
  String:适用于少量的字符串操作的情况

  StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况

  StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况

  附上自己测试的代码

  

    @Test
    public void testString(){
        String str_a = "hello";
        String str_b = "hello";
        System.out.println(str_a.hashCode());
        System.out.println(str_b.hashCode());
        str_a = str_a +" world";
        System.out.println("string修改后");
        System.out.println(str_a.hashCode());
        System.out.println(str_b.hashCode());
        StringBuffer stb_a = new StringBuffer("hello");
        StringBuffer stb_b = new StringBuffer("hello");
        System.out.println(stb_a.hashCode());
        System.out.println(stb_b.hashCode());
        stb_a.append(" world");
        System.out.println("StringBuffer修改后");
        System.out.println(stb_a.hashCode());
        System.out.println(stb_b.hashCode());

        System.out.println("比较hello和hello world的hashcode和前面定义的str_a 和修改后的str_a 是否相同");
        System.out.println("hello".hashCode());
        System.out.println("hello world".hashCode());
    }

 

 

 

 

   执行结果如下

 

   

99162322
99162322
string修改后
1794106052
99162322
643489709
171809144
StringBuffer修改后
643489709
171809144
比较hello和hello world的hashcode和前面定义的str_a 和修改后的str_a 是否相同
99162322
1794106052

 

posted @ 2018-02-24 16:12  小小小怪兽  阅读(1330)  评论(0)    收藏  举报