1
我想改变一个对象的引用,我写了下面的代码。Java - 如何使用方法更改引用?
public class Test {
public static void main(String[] args) {
Foo foo1 = new Foo();
Foo foo2 = new Foo();
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
change(foo1, foo2);
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
}
public static void change(Foo foo1, Foo foo2) {
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
foo1 = foo2;
System.out.println("the reference of foo1 is " + foo1);
System.out.println("the reference of foo2 is " + foo2);
System.out.println();
}
}
class Foo {
public Foo() {
// do nothing
}
}
我得到了以下输出。
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
the reference of foo1 is [email protected]
the reference of foo2 is [email protected]
change
的方法从[email protected]
改变foo1
提及[email protected]
在change
方法,但foo1
参考在main
方法并没有改变。为什么?
我不知道你所说的“改变对象的引用”的意思,但我强烈怀疑,你的问题将在[在此页面](https://stackoverflow.com/q/40480)上得到解答 - 这样我就很想将它作为一个副本来关闭它。 –
@Reimeus标记的副本不正确。问题是关于传递引用。 在Java中,引用是作为COPIES传递到方法中的。任何重新分配只保留在该范围的本地。 – Kon