结论:java传递的是值,而不是引用
来看三个程序
package test.example;
public class ParamTest {
public static void main(String args[]){
Employee a =new Employee("Aick");
Employee b = new Employee("Blick");
swap(a,b);
System.out.println("a name is "+ a.name);
System.out.println("b name is "+ b.name);
}
public static void swap(Employee a,Employee b)
{
Employee temp;
temp = a;
a = b;
b = temp;
}
}
class Employee{
double salary;
String name;
public Employee(String name){
this.salary = 1;
this.name = name;
}
}
结果是什么?
a name 还是 Alick
b name 还是Blick
因为是函数传递的是值,所以在swap产生的a,是一个新的引用,这个应用指向a指向的对象,
结束后就丢掉了
int a =1;
int b =1;
swap(a,b);//swap是交换两个数的函数
结果还是不变的
那有方法使他们改变吗?
有对Employ.属性进行访问交换
public void swap(Employee a, Employee b){
double temp = a.salary;
a.salary =b.salary;
b.salary = a.salary;
String tempname = a.name;
a.name =b.name;
b.name = tempname;
}