情况 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;
s2
和s1
都保留对同一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
的引用,而不是s2
s1
变量本身的引用,因为s1
没有其他"Hello"
引用。然后,当您同时打印s1
和s2
时,它们都在打印"Hello"
因为它们都包含"Hello"
的引用。
当你声明s1 = "hello changed";
时,s1
现在不再有"Hello"
的引用,而是包含String
值"hello changed"
的引用,该值位于不同的内存位置。但是s2
仍然具有String
值"Hello"
的引用,因为您尚未为s2
分配任何内容。所以现在s1
有"hello changed"
的参考,s2
有"Hello"
的参考。如果您打印s1
和s2
,他们将打印其相应的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.
如果您仍然感到困惑,请不要忘记评论它。谢谢。