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)
表达的很模糊,大概不明确例子中的值怎么传的。希望可以知道原理和明确的理论,不是只记住这种情况是这样。
First of all, Java is pass by value.
All "values" point to an object (except primitive types, which are themselves)
Because they are all values, yours only changed one value. Of course, the original value and the object it refers to are still there.
Because what you return is a value, this value points to an object, and of course it can also be modified.
To facilitate understanding, you can treat this value as a label (except for primitive types, of course), or if you have a C/C++ background, treat them as pointers/references.
P.S: The same is true for languages such as Python