Java在调用函数时有两种方法传递参数:按值传递和按引用传递。
基本类型的变量总是按值传递。
基本类型:
字节型byte 8位 短整型short 16位 整型int 32位 长整型long 64位
单精度float 32位 双精度double 64位
字符型char 8位
布尔型:boolean 8位
而对象是将对象的的引用或者说对象的首地址传递给方法,引用本身是按值传递的,也就是将引用copy给方法),通过对象的引用,方法可以直接操作该对象(当操作该对象时才能改变该对象,而操作引用时源对象是没有改变的)。
上一篇说到,Java在函数调用时,往新的frame中传递参数时会把参数拷贝一份过去,而在被调用函数的frame中对参数进行更改(即对值或者引用进行操作),不会对调用者的数据产生影响。
那么如何才能使调用者的参数产生改变呢?这里以swap函数为例
public class test {
public int a;
public int b;
//直接交换
public static void swap(int a,int b){
int t=a;
a=b;
b=t;
}
//数组交换
public static void swap(int arr[]){
int t=arr[0];
arr[0]=arr[1];
arr[1]=t;
}
//成员变量交换
public void swapNum(int a, int b) {
this.a = b;
this.b = a;
}
public static void main(String[] args) {
int a=1,b=2;
int[] arr={1,2};
swap(a,b);
System.out.print("直接交换结果:");
System.out.println(a+" "+b);
swap(arr);
System.out.print("数组交换结果:");
for(int i:arr){
System.out.print(i+" ");
}
test swap=new test();
swap.swapNum(a, b);
System.out.println();
System.out.print("成员变量交换结果:");
System.out.print(swap.a+" "+swap.b);
}
}
可以看出直接交换是没有对调用者的参数产生影响的。
成员变量交换
左边的this.a ,this.b为a,b的属性;右边的a,b为传进来的参数(局部变量)
swap函数中对a,b的属性进行了交换,swap.a是对属性的调用。
数组交换
数组本身是一个对象,如果传递数组的引用,则可以使原数组产生变化;如果将单个基本类型的数组元素传递给方法,因为这种元素是按值传递的,所以原数组并不会储存该方法执行修改后的值。
举个例子
public class test2 {
private String[] arr = {"2","4"};
void test(String[] arr){
arr[0] = "3";
System.out.println("传数组引用:"+arr[0]);
arr = new String[]{"6","8"};
System.out.println("传数组元素:"+arr[0]);
}
public static void main(String[] args){
test2 s = new test2();
s.test(s.arr);
System.out.println("数组接受到的值:"+s.arr[0]);
}
}