关于java的引用传递和值传递
public class TestArray {
public static void main(String[] args) {
//revise an array directly without return
String[] test = {"test"};
voidReturn(test);
System.out.println(test[0]);
//revise an array directly with return
String[] test2 = {"test2"};
String[] outtest2 = arrayReturn(test2);
System.out.println(outtest2[0]);
//revise an array by another way
String[] test3 = {"test3"};
voidReturn2(test3);
System.out.println(test3[0]);
}
public static void voidReturn(String[] a) {
String[] b = {"b"};
a = b;
System.out.println("a in voidReturn is "+ a[0]);
}
public static String[] arrayReturn(String[] a) {
String[] b = {"b"};
a = b;
System.out.println("a in arrayReturn is "+ a[0]);
return a;
}
public static void voidReturn2(String[] a) {
a[0] = "b";
System.out.println("a in voidReturn2 is "+ a[0]);
}
}
输出:
a in voidReturn is b
test
a in arrayReturn is b
b
a in voidReturn2 is b
b
在传递一个引用类型的时候,使引用类型指向别的引用类型,为什么在main方法中的值依然不变?(voidReturn方法)
作为返回值传出,可以修改,这是什么原理?(arrayReturn)
对引用了类型直接修改,可以改变值(voidReturn2)
表达的很模糊,大概不明确例子中的值怎么传的。希望可以知道原理和明确的理论,不是只记住这种情况是这样。
H.ero
10 years, 4 months ago