字符串对象是不可变的,但引用变量是可变的.这意味着什么? [英] String object is immutable but reference variable is mutable. What does that mean?

查看:65
本文介绍了字符串对象是不可变的,但引用变量是可变的.这意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Kathy Sierra Java书.我碰到了一个类似这样的问题:

I was studying Kathy Sierra Java book. I came across one question something like this:

public class A {
    public static void main(String args[]){
        String s1 = "a";
        String s2 = s1;
        //s1=s1+"d";
        System.out.println(s1==s2);
    }
}

输出: true

我在这里不明白的两点是:

Two points I didn't understand here are:

  1. 当我取消注释 s1 = s1 +"d" 时,输出将更改为 false .如果我用包装器 Integer int 替换String,也会发生同样的事情.
  2. 同样,当我将代码更改为使用 StringBuffer 时,如下所示:

  1. when I uncomment s1 = s1 + "d" output changes to false. Same thing happens if I replace String with wrapper Integer or int.
  2. Again, when I change my code to use StringBuffer like this:

StringBuffer sb = new StringBuffer("a"); 
StringBuffer sb2 = sb;
//sb.append("c");
System.out.println(sb == sb2);

现在输出不会改变,即使我取消注释 sb.append 语句,它也保持为 true .

now the output doesn't changes i.e. it remains true even if I uncomment the sb.appendstatement.

我无法理解这种奇怪的行为.有人可以解释一下我吗.

I can't understand this strange behavior. Can some one explain me.

推荐答案

s2 在第一种情况下是对 s1 的引用.在第二种情况下,将 + 转换为 s1.concat("d"),这将创建一个新字符串,因此引用 s1 s2 指向不同的字符串对象.

s2 is a reference to s1 in the first case. In the second case, + is translated to s1.concat("d") which creates a new string, so the references s1 and s2 point to different string objects.

对于 StringBuffer ,引用永远不会改变. append 更改缓冲区的内部结构,而不是对其的引用.

In the case of StringBuffer, the reference never changes. append changes the internal structure of the buffer, not the reference to it.

这篇关于字符串对象是不可变的,但引用变量是可变的.这意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆