情况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
对象不受影响。