这个问题产生的根源是,对于java中参数传递的误区:
原始类型按值传递;对象按引用传递。
其实不然。请记住,
java中,无论是原始类型还是对象,都是按值传递的。
这里的“值”可以简单的理解为“对象或原始类型在内存中的地址”(并不准确)。
插播两个概念,‘按值传递’和‘按引用传递’:
Pass-by-value:
The actual parameter (or argument expression) is fully evaluated and
the resulting value is copied into a location being used to hold the
formal parameter's value during method/function execution. That
location is typically a chunk of memory on the runtime stack for the
application (which is how Java handles it), but other languages could
choose parameter storage differently.
Pass-by-reference:
The formal parameter merely acts as an alias for the actual parameter.
Anytime the method/function uses the formal parameter (for reading or
writing), it is actually using the actual parameter.
不知如何翻译才不会有误解,便不翻了。逃)
回过头来看题主的问题,当调用
method(a,b);
时,是将a和b的地址传入方法method,那么
public static void method(Circle x,Circle y){
Circle tmp = x;
x = y;
y = tmp;
}
进入方法后,x初值为对象a的地址,y初值为对象b的地址;而进行交换后,只是将x指向了对象b的地址,y指向了对象a地址。而:
a和b的值并未交换。
好,现在再来看个例子:
Class User{
private String name;
.
.
.
}
public static void foo(User user){
user.setName("Max");// AAA
user = new User("Fifi");// BBB
user.setName("Rowlf");// CCC
}
public static void main(String[] args){
User basicUser = new User("Rover");
foo(basicUser );
}
请问,‘AAA’、‘BBB’、‘CCC’这3行代码执行完后,对象basicUser的name分别是什么?
‘AAA’行:name为‘Max’;
‘BBB’行:name为‘Max’;
‘CCC’行:name为‘Max’;
请思考下原因。
Ps: 若有纰漏有误之处,欢迎批评指正。