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
を介して2つのオブジェクトを設定していると、この出力に示すように、オブジェクトの一方のみが、変更された:私の記憶が正しければのでこの例でString helloWorldが変更されないのはなぜですか?この例では
Hello, World!
World!
Process finished with exit code 0
これは私を混乱させる:
- オブジェクトに渡すと、参照を渡すので、返さなくてもオブジェクト自体を変更することができます
- これは、私がArrayListを渡すことができる同じ理由です。同じArrayListを返さずに、それを前のArrayListに代入することなく、
main
にそれを操作します。 - 文字列はオブジェクトです。
なぜ文字列helloWorldが変更されませんでしたか?
文字列は変更できません。変更できません。 – chrylis