如何证明 java 中的字符串作为引用类型的合理性? 查看以下案例



情况 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

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

之后

String s2 = s1;

s2s1都保留对同一String的引用。

但之后

s2 = "hello changed";

s2持有对新String的引用,而s1仍然持有对原始String的引用。

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

好的,让我为您清除上述所有情况。

案例1:

创建String s1 = "Hello";时,编译器首先将String"Hello"放在内存位置,并将该内存位置的引用存储到变量s1中。那么你的变量s1有什么?只有"Hello"的参考.因此s1不包含Hello而是将内存位置作为参考。做?

然后当你声明String s2 = s1;时,你只存储Hello的引用,而不是s2s1变量本身的引用,因为s1没有其他"Hello"引用。然后,当您同时打印s1s2时,它们都在打印"Hello"因为它们都包含"Hello"的引用。

当你声明s1 = "hello changed";时,s1现在不再有"Hello"的引用,而是包含String"hello changed"的引用,该值位于不同的内存位置。但是s2仍然具有String"Hello"的引用,因为您尚未为s2分配任何内容。所以现在s1"hello changed"的参考,s2"Hello"的参考。如果您打印s1s2,他们将打印其相应的String"hello changed"和"您好"。你现在清楚了吗?如果尚未查看以下代码示例:

String s1 = "Hello"; // s1 has reference of "Hello"
String s2 = s1; // Now s2 has reference of "Hello" not s1
System.out.println(s1); // Prints "Hello"
System.out.println(s2); // Prints "Hello"
s1 = "hello changed"; // Now s1 has reference of "hello changed" not "Hello" but still s2 has reference of "Hello" because you did not changed it.
System.out.println(s1); // Prints "hello changed" 
System.out.println(s2); // Prints "Hello" because you did not changed it.

案例2:

String s1 = "Hello"; // s1 has reference of "Hello"
String s2 = s1; // Now s2 has reference of "Hello" not s1
System.out.println(s1); // Prints "Hello"
System.out.println(s2); // Prints "Hello"
s2 = "hello changed"; // Now s1 has reference of "hello changed" not "Hello" but still s2 has reference of "Hello" because you did not changed it.
System.out.println(s1); // Prints "Hello" because you did not changed it.
System.out.println(s2); // Prints "hello changed" because you changed it.

如果您仍然感到困惑,请不要忘记评论它。谢谢。

最新更新