简体   繁体   English

Java:传递对变量的引用作为方法的参数

[英]Java: Passing a reference to a variable as an argument for a method

When passing an object as an argument for a method, all changes that happen to the argument inside the method, affect the "original" object as well.将对象作为方法的参数传递时,方法内部参数发生的所有更改也会影响“原始”对象。 That's because the argument is a reference to the object.那是因为参数是对对象的引用。

But I also want to do the same with variables- I want all changes that happen inside the method to affect the "original" variable.但我也想对变量做同样的事情——我希望方法内部发生的所有变化都影响“原始”变量。 But I don't know how.但我不知道怎么做。 I want to do this, because some times more than one local variables need to be processed in the same way.我想这样做,因为有时需要以相同的方式处理多个局部变量。

How can I pass a reference to a variable as an argument for a method?如何将变量的引用作为方法的参数传递?

There is no other choice than to store the variable inside an object, and to pass the object.除了将变量存储在对象中并传递对象之外,别无选择。 All arguments are passed by value in Java. Java 中的所有参数都是按值传递的。

The object can be this (ie the variable is in fact a field of the current object).对象可以是this (即变量实际上是当前对象的一个​​字段)。

Can you clarify what you mean by the word "variable"?你能解释一下“变量”这个词是什么意思吗? Do you mean a local reference inside the method, a primitive that's passed in, or something else?你的意思是方法内部的局部引用,传入的原语,还是其他什么?

Java references and primitives are passed by value. Java 引用和原语是按值传递的。 You cannot alter them, no matter how much you may want to.无论您多么想更改它们,您都无法更改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM