通过引用递归传递对象?爪哇
因此,我有一个算法,迫使我递归地传递一个对象作为参数,并在不同的递归深度上设置该对象的值。问题是 Java 不允许我这样做,因为它们按值传递或其他东西只是让我感到困惑。如何确保传入的对象保留设置的值?
So I have an algorithm that forces me to pass in an object as a parameter recursively and on different depths of the recursion it sets the values of the object. The problem is Java isn't allowing me to do this because they pass in by value or something else that is just messing me up. How can you make sure that the object passed in retains the value set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Java 中,您永远不会将对象作为参数传递。您可以传递引用或原始值。参数始终按值传递。 Java 根本没有引用传递。
如果您要传递对对象的引用,并且希望确保您调用的代码不会更改该对象内的数据,则您的选择是:
编辑:只是为了清楚起见,如果您有:
那么
f
的值不是一个Foo
对象。它是对Foo
对象的引用。如果您现在调用:,则
f
的值将被复制为doSomething
中参数的原始值。这种行为基本上就是值传递的定义。doSomething
无法改变f
的值 - 之后它仍然会引用同一个对象。该对象内的数据可能已更改,但它不会是不同的对象。打个比方:如果我给你一份我的地址副本,你可以去粉刷前门,但你不能改变我住的地方。
You never pass an object as an argument in Java. You either pass a reference or a primitive value. The argument is always passed by value. Java doesn't have pass-by-reference at all.
If you're passing in a reference to an object, and you want to make sure the code you call doesn't change the data within that object, your options are:
EDIT: Just to make it clear, if you have:
then the value of
f
is not aFoo
object. It's a reference to aFoo
object. If you now call:then the value of
f
is copied as the original value of the parameter withindoSomething
. That behaviour is basically the definition of pass-by-value. There's nothingdoSomething
can to do change the value off
- it will still refer to the same object afterwards. The data within that object may have changed, but it won't be a different object.In a real-world analogy: if I give you a copy of my address, you can go and paint the front door, but you can't change where I live.
正如 Jon 所说,所有非基元都是通过传递引用的副本来传递的。你别无选择。因此,如果对象是可变的,您的递归方法应该能够更新该对象。但是,您不能重新分配引用并期望它传播回调用堆栈。请记住,字符串是不可变的。
换句话说,如果执行以下操作,则不会更改传递的对象:
上面更改了对
o
的本地引用,但没有更改对o
的调用者引用>。如果您需要执行类似的操作,则需要返回o
。As Jon states, all non-primitives are passed by passing a copy of the reference. You don't have a choice. So your recursive method should be able to update the object if it is mutable. HOWEVER, you can't reassign a reference and expect it to propagate back up the call stack. And remember that Strings are not mutable.
In other words, if you do the following, you have not changed the object that was passed:
The above changes the local reference to
o
but does not change the caller's reference too
. If you need to do something like this you would need to returno
.