java的传递是引用传递还是值传递困扰了不少人~~
虽然java通过引用操作对象,但是java传递方法参数时传递的是值而不是引用
这里可能有同学要问了,楼主的例子的确是通过引用修改了对象呀~
Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.
java实际上传递的是一个引用的拷贝
举一个例子
让我们来看看原因~
前三行都没有问题,为啥第四行会出现 0,0 的结果,如果是通过引用传递,就应该改动了对象的值呀
原因是当你传了参数过去时,等于复制了一个引用指向同一个对象
如下图,两个引用指向同一个对象,当你通过method reference 修改对象时,对象是真的被改变了~
但是我们的swap函数中让method reference 指向了其他的对象,而我们原来的original reference 指向的对象没有任何变化,当出了函数的时候, method reference 就会被丢弃~~
所以~~第三行出现的原因,我们通过引用改动了对象的值,出函数original reference 指向的 对象变了,打印的值也要变
第四行,我们只是改动了copy reference 的指向,original reference 的指向没有变化,打印的值不变
Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
原文:http://sunway.iteye.com/blog/202512
|