作者awert ( )
看板java
标题Re: [问题] 用函数让字串阵列反转的问题
时间Sat Apr 14 13:27:44 2012
※ 引述《pa015596 (sdfgdgf)》之铭言:
: 当在main呼叫reverse(data)时 data这个阵列的值却没被修改
: 请教大大为何str=str2这行指令不能将结果修改到data
Java 永远是 pass-by-value。
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.1
When the method or constructor is invoked (§15.12),
the values of the actual
argument expressions initialize newly created parameter variables, ...
也就是说,当 method, constructor 被呼叫时,里面的 parameter variable 是新建出来
的参数,而不是 reference 本身。
看一下这个例子
public static void main(String[] args) {
People mary = new People("Mary");
transfer(mary);
System.out.println(mary.getName()); // still Mary, not John
}
private static void transfer(People p) {
p = new People("John");
}
为什麽不会变 ? 让我们看一下实际发生的事
People mary = new People("Mary");
mary 0xAABBCC
------------- -----------------
| 0xAABBCC | ------------> | People("Mary")|
------------- -----------------
transfer(mary);
mary 0xAABBCC
-------------- -----------------
| 0xAABBCC | ------------> | People("Mary")|
-------------- -----------> -----------------
p /
--------------/
| 0xAABBCC |
--------------
当 transfer 被呼叫时,parameter p 不是 mary, 而是 mary 的复制品。
因此当执行到 p = new People("John") 时
mary 0xAABBCC
-------------- -----------------
| 0xAABBCC | ------------> | People("Mary")|
-------------- -----------------
p 0x112233
-------------- -----------------
| 0x112233 | ------------> | People("John")|
-------------- -----------------
这就是实际发生的事。参数 p 被指向了 John,但是参数 mary 仍然指向 Mary。
System.out.println(mary.getName())
mary 0xAABBCC
-------------- -----------------
| 0xAABBCC | ------------> | People("Mary")| ==> 印出 Mary
-------------- -----------------
==========================================================
这样子你应该可以理解为什麽 str1 = str2 不会达到你要的效果。
--
We who cut mere stones must always be envisioning cathedrals.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.39.55.118
※ 编辑: awert 来自: 114.39.55.118 (04/14 13:30)
1F:推 hate9527:如果people不new 用set get 结果似乎会不一样 04/14 13:54
2F:推 pa015596:谢谢大大详细的解说 04/14 14:00
3F:→ awert:@hate9527 > 用setter当然会不一样 04/14 14:04
4F:推 hate9527:我是提醒提问人呀 04/14 17:29
5F:→ forthewill:推..原po真热心 04/15 02:03
6F:推 Chrisshan:热心给推! 04/29 22:43