简体   繁体   English

引用同一字符串对象的两个Java变量不同步

[英]Two java variables referencing same string object don't sync

From my novice perspective of Java object, if two variables referencing one object, updating one variable should do the same to the other, as the code shows below: 从Java对象的新手角度来看,如果两个变量引用一个对象,则更新一个变量应与另一个变量相同,如代码所示:

SomeObject s1 = new SomeObject("first");
SomeObject s2 = s1;
s2.setText("second");
System.out.println(s1.getText()); // print second
System.out.println(s2.getText()); // print second as well

I referenced the code from this thread . 我从该线程引用了代码。

However, this doesn't apply to String class. 但是,这不适用于String类。 See code below: 参见下面的代码:

String s_1 = new String("first");
String s_2 = s_1;
s_2 = "second";
System.out.println("s_1: " + s_1 + " s_2:  " + s_2); 
//s_1 appears to be "first" and s_2 "second"

Is this because the difference between String class and self-declared class? 这是因为String类和自声明类之间的区别吗? Thank you for your help! 谢谢您的帮助!

No, the difference is in the kind of change you make. 不,区别在于您所做的更改。

This code: 这段代码:

s2.setText("second")

doesn't change the value of either s2 or s1 . 不会更改s2s1的值。 Both s1 and s2 refer to the same object as they did before... but the contents of the object has changed. s1s2引用了与以前相同的对象...但是对象的内容已更改。

Compare that with this code: 将其与以下代码进行比较:

s_2 = "second";

Here you're changing the value of s2 to be a reference to a different object. 在这里,您将s2的值更改为对其他对象的引用。 Changing the value of s_2 doesn't change the value of s_1 at all - it still refers to the same object that it did before. 更改s_2的值根本不会更改s_1的值-它仍然引用以前与之相同的对象。

You probably want to read up on the differences between variables, objects and references - once you can get that clear in your head, everything else will make a lot more sense. 您可能想阅读一下变量,对象和引用之间的区别 -一旦您清楚地知道了,其他所有内容都将变得更加有意义。

A String object can be initialized without the constructor being called. 可以在不调用构造函数的情况下初始化String对象。 So when you initialize s_2 to s_1 , it is given the value of it and when you initialize s_2 = "second" it is overwritten. 因此,当您将s_2初始化为s_1 ,会得到它的值,而当您将s_2 = "second"初始化时,它将被覆盖。 It is same as s2 = s1 and then s2 = new SomeObject ("second") s2 = s1相同,然后与s2 = new SomeObject ("second")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM