在Java中并不存在引用传递(即地址传递),对于变量(可以是基本数据类型,也可以是引用数据类型)而言,可以理解为就是一个地址。传递,存在着拷贝操作。举个方法测试:
public class Terst4 {
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("In swap: a = " + a + ", b = " + b);
}
public static void swap(Person c, Person d) {
Person temp = null;
temp = c;
c = d;
d = temp;
System.out.println("In swap: " + c + ", " + d);
}
public static void main(String[] args) {
int a = 1;
int b = 2;
Person c = new Person("c");
Person d = new Person("d");
System.out.println("对于基本数据类型");
System.out.println("Before swap: a = " + a + ", b = " + b);
swap(a, b);
System.out.println("After swap: a = " + a + ", b = " + b);
System.out.println("对于引用数据类型");
System.out.println("Before swap: " + c + ", " + d);
swap(c, d);
System.out.println("After swap: " + c + ", " + d);
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "My name is " + this.name + ".";
}
} |