java中通过引用传递?
我正在尝试为 Android GSM 构建一个小游戏。我有很多单位,所有单位都有目的地。为了计算目的地,我使用了一个名为 CalDes 的函数。这个函数 CalDes 正在计算我单位的速度。因此,我发送了一些变量,我必须对其进行编辑并再次使用它们。为此,我必须发送这些变量作为参考。这是一个简单的 C++ 如何在 java 中做到这一点?
void swap(SomeType& arg1, Sometype& arg2) {
SomeType temp = arg1;
arg1 = arg2;
arg2 = temp;
}
...
SomeType var1 = ...; // value "A"
SomeType var2 = ...; // value "B"
swap(var1, var2); // swaps their values!
I'm trying to build a litle gam for android GSMs. I hava lots of units and all of them have destinations. To calculate destination I'm using a function called CalDes. This function CalDes is calculating my unit's speed. So I'm sending some variables into which I have to edit and use em again. For this I have to send these variables with reference. Here is a simple for C++ How to do that in java?
void swap(SomeType& arg1, Sometype& arg2) {
SomeType temp = arg1;
arg1 = arg2;
arg2 = temp;
}
...
SomeType var1 = ...; // value "A"
SomeType var2 = ...; // value "B"
swap(var1, var2); // swaps their values!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 根本没有引用传递。您有几个选择:
以数组形式传递数据:
...但是使用它在调用代码中很痛苦:
创建一个具有公共
SomeType
成员的对象,并传递在对象引用中。这与 #1 非常相似,但调用代码可能更方便。
Java doesn't have pass-by-reference at all. You have a couple of options:
Pass the data in an array:
...but using it is a pain in the calling code:
Create an object that has public
SomeType
members, and pass in the object reference.Which is very similar to #1, but probably more convenient to work with from calling code.
在 Java 中不可能,请阅读: http:// www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Not possible in Java, read: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
在 Java 中,每个对象总是通过引用传递。但不能通过引用传递变量。如果您确实需要它,则必须再使用一种间接方式。
In Java, every object is always passed by reference. But you cannot pass variables by reference. If you really need that, you have to use one more indirection.