简述:
对于java中传递的参数, 分为两类,基本数据类型作为参数,如int,double等
以及 以某个对象类作为参数进行传递,在函数中修改参数的结果是不同的
1. 基本数据类型传递的是值
2. 引用数据类型传递的是地址
但是究竟哪些是基本类型呢? 下面做了比较粗犷的测试
以下测试的代码中,作为输入情况,分为五种:
先后传递五种不同的变量作为参数,观察是传形参,还是传引用
a) 一个自己定义的对象IntNum intNum, 修改其成员变量num
b) 普通的一个int num
c) String 变量
d) List 变量
e) Array 变量
结果发现:
b, c, 都被视为基本数据类型,只是传递一个值,并没有新建一个对象,所以修改之后,值都没有变
剩余的传递过去的都是地址,都发生了改变 其中Array类型也发生了改变
测试代码:
package test.generic;
import java.util.ArrayList;
class IntNum{
private int num;
public IntNum(int num){
this.num = num;
}
public void setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
class ParameterChanger{
//here parameter is an IntNum class
public void ChangeToZero(IntNum intNum){
intNum.setNum(0);
}
//here parameter is basic data type int
public void ChangeToZero(int num){
num = 0;
}
public void ChangeStringToXXX(String str){
str = "XXX";
}
public void ChangeListOnIndex0(ArrayList array){
array.set(0, 0);
}
public void ChangeArrayOnIndex0(int[] array){
array[0] = 0;
}
}
public class TestReferencePassingOrNot {
public static void main(String[] args) {
ParameterChanger parameterChanger = new ParameterChanger();
IntNum intNum = new IntNum(100);
System.out.println("Pass An Object Class as parameter: ");
System.out.println("Number in IntNum Class before change: " + intNum.getNum());
parameterChanger.ChangeToZero(intNum);
System.out.println("Numberin IntNum Class after change: " + intNum.getNum());
System.out.println("\nPass An Basic Data Type int as parameter: ");
int num = 100;
System.out.println("Number int before change: " + num);
parameterChanger.ChangeToZero(num);
System.out.println("Number int after change: " + num);
System.out.println("\nPass String as parameter: ");
String str = "TEST_STRING";
System.out.println("String str before change: " + str);
parameterChanger.ChangeStringToXXX(str);
System.out.println("String str after change: " + str);
System.out.println("\nPass List as parameter: ");
ArrayList list = new ArrayList();
list.add(100);
System.out.println("list.get(0) before change: " + list.get(0));
parameterChanger.ChangeListOnIndex0(list);
System.out.println("list.get(0) after change: " + list.get(0));
System.out.println("\nPass Array as parameter: ");
int array[] = new int[1];
array[0] = 100;
System.out.println("array[0] before change: " + array[0]);
parameterChanger.ChangeArrayOnIndex0(array);
System.out.println("array[0] after change: " + array[0]);
}
}
输出: