Java – 字符串和数组引用
刚开始学习Java,发现字符串和数组都是引用类型。 我不明白以下问题:
String a = "a1"; String b = "a2"; a=b; a = "rrr"; System.out.println(a); System.out.println(b); int[] arr1 = {1,2,3}; int[] arr2 = arr1; arr2[0]= 19; System.out.println(arr1[0]);
当我打印它时,我得到: "rrr" "a2" 10
当使用数组时 – 我知道它们都指向同一个对象,所以如果我改变单元格 – 我看到arr1和arr2的区别。
关于“字符串” – 根据我的理解,当我这样做时:a = b它不应该是:“让b
上的同一个对象上的a
点指向” – 意思是如果我改变它,它们都需要被改变?
谢谢!!
在数组的情况下,您实际上是在修改数组,因此如果一个引用被更改,另一个引用也是如此。
在字符串的情况下,您不是在修改对象,而只是为该引用分配不同的对象。 正如你所说: a=b
意味着“让一个点与b指向同一个对象”。 遵循同样的思路, a="rrr"
意味着“让一个点到文字”rrr“”,这与b无关。
因此, 重新分配与修改是不同的。
如果你有
String a = "foo"; String b = a;
那么你已经指定了 b
来引用同一个对象作为a
。 如果你这样做
b = "bananas";
然后你没有修改字符串,你已经重新分配了 b,所以它不再引用同一个对象a
。
另一方面
int[] c = { 1, 2, 3 }; int[] d = c;
这里我们再次指定与c
相同的对象(数组)。 如果你那么做这样的事情:
d[0] = 10;
那么你正在修改 c
和d
引用的数组的内容。
你有3个字符串对象和1个数组对象。
“a1”,“a2”,“rrr”
{1,2,3}
String a = "a1"; // a points to a new object "a1" String b = "a2"; // b points to a new object "a2" a=b; // a points to b's object "a2" a = "rrr"; // a points to new object "rrr" System.out.println(a); // prints "rrr" to console System.out.println(b); // Prints "a2" to console int[] arr1 = {1,2,3}; // arr1 points to new array {1,2,3} int[] arr2 = arr1; // arr2 points to array in arr1 {1,2,3} arr2[0]= 19; // modifies the array arr2 points to {19, 2, 3} System.out.println(arr1[0]); // Prints "19" to console
首先,String是不可变的。 Immutalbe意味着您无法更改对象本身,但您可以更改引用。 就像你的情况一样 –
String a = "a1"; // a is a reference variable and point to new object with value "a1" String b = "a2"; // b is a reference and point to new object with value "a2" a=b; // now a is referencing same object as b is referencing, a and b value is "a2" a = "rrr"; // at this time "rrr" is creating a new String object with value "rrr" and now a is pointing to this object.
所以b仍指向“a2”,现在指向新对象“rrr”。 这就是为什么两者都打印出不同的价值。
System.out.println(a); System.out.println(b);