class OtherObject {
String innerString;
OtherObject(String x) {innerString = x;}
}
class Playground {
public static void mutate(OtherObject toMutate) {
toMutate.innerString = toMutate.innerString.substring(toMutate.innerString.length()/2);
}
public static void mutate(String toMutate) {
toMutate = toMutate.substring(toMutate.length()/2);
}
public static void main(String[] args) {
String helloWorld = new String("Hello, World!");
OtherObject helloWorld2 = new OtherObject("Hello, World!");
mutate(helloWorld);
mutate(helloWorld2);
System.out.println(helloWorld);
System.out.println(helloWorld2.innerString);
}
}
在本例中,我已通过方法mutate
设置两个对象,并且只有对象之一改变,如图中的输出:为什么在这个例子中没有改变String helloWorld?
Hello, World!
World!
Process finished with exit code 0
这混淆我因为如果我记错:
- 对象,当传入的方法是传递引用,因此即使没有返回,对象本身可以改变
- 这是我可以传递ArrayList到上午ethod并操作它,而不必返回相同的ArrayList并将其分配给
main
中的前一个ArrayList。 - 字符串是一个对象。
为什么String helloWorld没有改变?
字符串是不可变的 - 它们不能改变。 – chrylis