Java 方法不会更改参数对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16513178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java method doesn't change parameter objects
提问by hp58
I have a function like this:
我有一个这样的功能:
public static int partition(List list, ListElement elemL, ListElement elemR){
ListElement elemX;
...
elemR = elemX.next;
return x;
}
And at the end of the funktion the elemRis changed, but after calling the function from the main method the parameter elemRhas still the same value like before the function call. What's the problem? How can i change this ListElement and "save" this change after the function is called without changing the return type to ListElement (i need the integer return value too)?
在函数结束时,elemR发生了变化,但是在从 main 方法调用函数之后,参数elemR仍然具有与函数调用之前相同的值。有什么问题?如何在调用函数后更改此 ListElement 并“保存”此更改而不将返回类型更改为 ListElement(我也需要整数返回值)?
回答by boring32
Java functions parameters are called by reference name, meaning that when you place an object as an function argument, the JVM copies the reference's value to a new variable, and passes it to the function as an argument. If you change the contents of the object, then the original object will change, but if you change the actual value of the reference, then these changes will be destroyed when the function ends.
Java 函数参数通过引用名称调用,这意味着当您将对象作为函数参数放置时,JVM 会将引用的值复制到一个新变量,并将其作为参数传递给函数。如果你改变了对象的内容,那么原来的对象就会改变,但是如果你改变了引用的实际值,那么这些改变会在函数结束时被销毁。
I hope it helps
我希望它有帮助