一、值传递和引用传递
在程序设计语言中将参数传给方法或函数的方式目前有两种:一种是值传递,一种是引用传递。
值传递表示将实参的值传递给方法;引用传递表将实参a的地址引用传递给方法。
Java是采用值传递的,Java程序中的方法得到的总是实参值的拷贝,
二、代码运行
我们来看下下面代码的运行结果
public class Main {
public static void main(String[] args) {
SingleInstance instance = SingleInstance.getInstance();
Student a = new Student();
Student b = new Student();
a.setName("zhangsan");
b.setName("lisi");
System.out.println(a);
System.out.println(b);
swap1(a,b);
System.out.println(a);
System.out.println(b);
swap(a,b);
System.out.println(a);
System.out.println(b);
}
private static void swap1(Student e, Student f) {
String name = e.getName();
e.setName(f.getName());
f.setName(name);
}
private static void swap(Student e, Student f) {
Student a= e;
e=f;
f=a;
}
}
结果为
Student{name='zhangsan'}
Student{name='lisi'}
Student{name='lisi'}
Student{name='zhangsan'}
Student{name='lisi'}
Student{name='zhangsan'}
从结果我们可以看出执行swap1方法的进行了交换,这是因为a,b指向的地址没有改变,改变的是指向地址所指向的name发生了改变
而swap方法执行时,创建了a' 和 b',虽然它们的值或地址确实发生了改变,但是方法执行完后,a'、b'出栈,没有影响到a,b,所以没有交换
swap1方法执行前
swap1 方法执行中
swap1方法执行后
然后是swap方法执行前
swap方法执行中
swap方法执行后
所fang
我们再看一组例子
public class Main {
public static void main(String[] args) {
int c =10;
int d=20;
Integer e =10;
Integer f=20;
swap(c,d);
System.out.println(c);
System.out.println(d);
swap(e,f);
System.out.println(e);
System.out.println(f);
}
private static void swap(int a, int b) {
int c =a;
a=b;
b=c;
}
private static void swap(Integer a, Integer b) {
Integer c =a;
a=b;
b=c;
}
}
结果为:
10
20
10
20
我们发现其c,d;e,f并没有因为方法而改变;这是因为无论是基本类型还是封装好的Integer类型,都没有改变实际上的值。
方法执行时,栈里放入了10,20,也确实进行了交换;但方法执行完毕时也进行了出栈,但c和d没有进行过交换
方法执行前
方法执行中
方法执行完