如何在Java中将字符串作为引用类型进行对齐?上面的示例如何不显示

问题描述 投票:-1回答:1

情况1-

        String s1 = "Hello";
        String s2 = s1; //now has the same reference as s1 right?

        System.out.println(s1); //prints Hello
        System.out.println(s2); //prints Hello

        s1 = "hello changed"; //now changes s2 (so s1 as well because of the same reference?) to  Hello changed

        System.out.println(s1); //prints Hello changed 
        System.out.println(s2); //prints Hello  (why isn't it changed to  Hello changed?)

这种情况的输出是显而易见的。

情况2-

        String s1 = "Hello";
        String s2 = s1; //now has the same reference as s1 right?

        System.out.println(s1); //prints Hello
        System.out.println(s2); //prints Hello

        s2 = "hello changed"; //now changes s2 (so s1 as well because of the same reference?) to  Hello changed

        System.out.println(s1); //prints Hello (why isn't it changed to Hello changed?)
        System.out.println(s2); //prints Hello changed

我想清除引用类型的混乱。

java string value-type reference-type
1个回答
0
投票

之后

String s2 = s1;

s2s1都引用相同的String

但之后

s2 = "hello changed";

[s2保留对新String的引用,而s1仍然保留对原始String的引用。

String是不可变的,因此您不能更改现有String对象的状态。为String变量分配新值只会使该变量引用一个新的String对象。原始的String对象不受影响。

© www.soinside.com 2019 - 2024. All rights reserved.