关于java的引用传递和值传递
迷茫
迷茫 2017-04-17 11:45:17
0
2
633
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)
表达的很模糊,大概不明确例子中的值怎么传的。希望可以知道原理和明确的理论,不是只记住这种情况是这样。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
小葫芦

First of all, Java is pass by value.
All "values" point to an object (except primitive types, which are themselves)

When passing a reference type and making the reference type point to another reference type, why does the value in the main method still remain unchanged? (voidReturn method)

Because they are all values, yours only changed one value. Of course, the original value and the object it refers to are still there.

It is passed as a return value and can be modified. What is the principle of this? (arrayReturn)

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

阿神
我喜欢把引用理解为“地址”的概念,引用传值传的是一份“地址的拷贝”,通过“地址的拷贝”修改对象值可以成功,但通过“地址的拷贝”修改地址是不会生效的,所以voidReturn2可以修改,voidReturn不会修改;
至于arrayReturn,可以看成是返回了一个地址,而String[] outtest2 = arrayReturn(test2)这句代码会让outtest2拷贝了一份返回的地址,当然是可以取到对象值的。
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template