[code="java"]package Facade;
public class Parameters {
public static void mystery(int[] b, int x){
b[0] = 3;
b = new int[4];
b[3] = 5;
x = 2;
}
public static void main(String[] args){
int[] a = {9,8,7,6};
int x = 1;
mystery(a,x);
a[x] = 1;
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
}
}
[/code]
请写出 输出结果:
我认为 这个结果是 9176。但是和答案不一样 ,有点搞不懂,请高手说明一下
[code="java"]
public class Parameters {
public static void mystery(int[] b, int x){
b[0] = 3; //因为传的是数组对象,所以会修改原来的数组a,此时b=a={3,8,7,6}
b = new int[4];//b现在不在引用a数组了,注意此时b=new int[4]而a={3,8,7,6}
b[3] = 5;
x = 2;//参数x是基本类型,不改变原来的实参的值,
}
public static void main(String[] args){
int[] a = {9,8,7,6};
int x = 1;
mystery(a,x);
//执行完mystery(a,x);之后,a={3,8,7,6},x = 1;
a[x] = 1;//a={3,1,7,6}
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
}
}
[/code]
就是java传参数的问题
java的参数如果是基本类型就是传值,如果是对象类型,那就是传引用
[quote]mystery(a,x); [/quote]
因为这里数组是传指针的,也就是 a 会被 mystery 改掉;