java 如果字符串对象是不可变的,那么为什么内容会改变?[duplicate]

jtw3ybtb  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(99)
    • 此问题在此处已有答案**:

(19个答案)
How is String in Java an immutable object, but I can still change its value after creating one? [duplicate](2个答案)
3年前关闭。

public class HelloWorld{

     public static void main(String []args){
         
        String s="java";
         s="world";
         
        System.out.println(s);
     }
}

输出:
世界

gmol1639

gmol16391#

代码中有两个String对象:"java""world"。它们都是不可变的(除非使用反射并依赖JDK内部)。s变量首先指向第一个,然后指向第二个,但它们是独立的对象。
之后:

String s="java";

你的记忆里有这样的东西

+−−−−−−−−−−+
s:Ref3243−−−−−>| (string) |
               +−−−−−−−−−−+      +−−−−−−−−−+
               | value:   |−−−−−>| (array) |
               | ...      |      +−−−−−−−−−+
               +−−−−−−−−−−+      | 0: 'j'  |
                                 | 1: 'a'  |
                                 | 2: 'v'  |
                                 | 3: 'a'  |
                                 +−−−−−−−−−+

然后

s="world";

您拥有:

+−−−−−−−−−−+
               | (string) |
               +−−−−−−−−−−+      +−−−−−−−−−+
               | value:   |−−−−−>| (array) |
               | ...      |      +−−−−−−−−−+
               +−−−−−−−−−−+      | 0: 'j'  |
                                 | 1: 'a'  |
                                 | 2: 'v'  |
                                 | 3: 'a'  |
                                 +−−−−−−−−−+
               +−−−−−−−−−−+   
s:Ref6449−−−−−>| (string) |   
               +−−−−−−−−−−+      +−−−−−−−−−+
               | value:   |−−−−−>| (array) |
               | ...      |      +−−−−−−−−−+
               +−−−−−−−−−−+      | 0: 'w'  |
                                 | 1: 'o'  |
                                 | 2: 'r'  |
                                 | 3: 'l'  |
                                 | 4: 'd'  |
                                 +−−−−−−−−−+

因此,末尾的println显示了第二个字符串的内容。
上面显示的value成员在任何给定的JDK实现中都可以称为value,也可以不称为value,它是一个私有数据成员。

相关问题