前一段时间看了一道题有两个选项叫做call by reference和call by value觉得有些疑惑,好像没怎么听过,后来才明白原来是值传递的问题后来还面试的时候还真遇到了这样的题,就觉得应该仔细分析一下。public class CallValue {
private int x = 3;
private int y = 4;
static void test1(CallValue c){
c.x = 4;
c.y = 5;
}
static void test2(int x,int y){
x = 6;
y = 7;
}
public static void main(String args[]){
CallValue list = new CallValue();
test1(list);
System.out.println(list.x +" " + list.y);
test2(list.x,list.y);
System.out.println(list.x +" "+ list.y);
}
}
像这样,最终会输出两个4 5;这是最简单的理解,当调用test1的时候传的是引用,也就是call by reference。他可以改变引用的值,但本身引用不可改变。当调用test2的时候,也就是call by value,他相当于拷贝了一份x和y,所以实例list中的x和y都没有变。java里所有的参数传递应该都是拷贝的,这一点很重要。未完待续。。。。
public class CallValue {
private int x = 3;
private int y = 4;
static void test1(CallValue c){
c.x = 4;
c.y = 5;
}
static void test2(int x,int y){
x = 6;
y = 7;
}
public static void main(String args[]){
CallValue list = new CallValue();
test1(list);
System.out.println(list.x +" " + list.y);
test2(list.x,list.y);
System.out.println(list.x +" "+ list.y);
}
}