String 是 java 中的一个“特殊”对象。它是一个不可变对象(固定且无法修改),并且是唯一可以在没有 new 关键字的情况下声明的对象。
如果您使用 StringBuilder,StringBuffer 这些是可变字符串,您的值将在更改时被修改。
当您深入研究时,Java String 会带来许多令人困惑的理解。当您使用“==”时,具有相同值的 2 个不同字符串返回相同的内存地址引用。例如。
String a1 = "abc"
String a2 = "abc"
a1 == a2 //returns true because a1 and a2 points to same reference (but not always!)
a1 == new String("abc") //returns false
/**Do use "equals", not == for string's value comparison**/
如果你能把注意力集中在内存对象引用上:
String s1 = "Hello, World!"; //let's say it's allocated to memory address 0x0012
String s2 = s1; //s2 points to same memory address 0x0012
s1 = "Goodbye, World!"; //s1 points to new memory address 0x1113
System.out.println(s2) //printing value in still in memory address 0x0012
相当于,s1指向新Object,s2指向旧Object。
当您参考您的 Point 示例时
Point p1 = new Point(1, 1);
Point p2 = p1; //p2 is referring to p1's memory address
p1.x = 5;
p1 = new Point(2,2); //Assign to new memory address, here is like the line for s1="Goodbye,world"
System.out.println(p2.x); //You now still get 5, because it's still old object.
因此,要修复可变字符串,您需要更改“Class”.“method”之类的内容,以保留正在修改的相同对象。因此类似于:
StringBuilder sb1 = new StringBuilder("Hello World");
StringBuilder sb2 = sb1; //Points to same reference address.
sb1.append("Goodbye World");
System.out.println(sb2.toString()); //Now you get Hello WorldGoodbye World.
sb1.setLength(0).append("Goodbye World"); //clear then set to new value.
System.out.println(sb2.toString()); //Now you get Goodbye World.