在 Java 中重新分配对象引用
Reassigning Object References in Java
我只是想澄清一件事。为什么 person1 和 person2 仍然引用同一个对象?
class Person{
private String name;
Person(String newName) {
name = newName;
}
public String getName() {
return name;
}
public void setName(String val) {
name = val;
}
}
class Test {
public static void swap(Person p1, Person p2) {
Person temp = p1;
p1 = p2;
p2 = temp;
}
public static void main(String args[]) {
Person person1 = new Person("John");
Person person2 = new Person("Paul");
System.out.println(person1.getName()+ ":" + person2.getName());
swap(person1, person2);
System.out.println(person1.getName()+ ":" + person2.getName());
}
}
输出将是:
John:Paul
John:Paul
我想知道为什么约翰和保罗没有交换?
Java 不是传递引用。
这意味着您无法在方法内交换调用方范围内变量的内容。
您所做的只是在 swap
方法中交换 local 变量 p1
和 p2
的内容。这对 main
.
中的变量没有影响
请注意,此 "problem" 仅适用于(局部)变量。您当然可以交换一个对象的实例字段,这对碰巧引用了同一对象实例的任何其他人都是可见的。
我只是想澄清一件事。为什么 person1 和 person2 仍然引用同一个对象?
class Person{
private String name;
Person(String newName) {
name = newName;
}
public String getName() {
return name;
}
public void setName(String val) {
name = val;
}
}
class Test {
public static void swap(Person p1, Person p2) {
Person temp = p1;
p1 = p2;
p2 = temp;
}
public static void main(String args[]) {
Person person1 = new Person("John");
Person person2 = new Person("Paul");
System.out.println(person1.getName()+ ":" + person2.getName());
swap(person1, person2);
System.out.println(person1.getName()+ ":" + person2.getName());
}
}
输出将是:
John:Paul
John:Paul
我想知道为什么约翰和保罗没有交换?
Java 不是传递引用。
这意味着您无法在方法内交换调用方范围内变量的内容。
您所做的只是在 swap
方法中交换 local 变量 p1
和 p2
的内容。这对 main
.
请注意,此 "problem" 仅适用于(局部)变量。您当然可以交换一个对象的实例字段,这对碰巧引用了同一对象实例的任何其他人都是可见的。