Java-如何使用方法更改引用?
我试图更改对象的引用,并编写了以下代码Java-如何使用方法更改引用?,java,reference,Java,Reference,我试图更改对象的引用,并编写了以下代码 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
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 Foo@15db9742
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@6d06d69c
the reference of foo2 is Foo@6d06d69c
the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c
change
方法将foo1
的引用从Foo@15db9742
至Foo@6d06d69cchange
方法中的,但是foo1
的引用在main
方法中没有改变。为什么?在Java中,方法的所有参数都是按值传递的。注意,作为对象引用的非原语类型的变量也按值传递:在这种情况下,引用按值传递
因此,在您的情况下,您在函数中所做的修改不会更改主函数中使用的对象我不知道您所说的“更改对象的引用”是什么意思,但我强烈怀疑您的问题会得到回答,以至于我很想将其作为副本关闭。@Reimeus标记的副本不正确。问题是关于传递参考资料。在Java中,引用作为副本传递到方法中。任何重新分配仅限于该范围。