gpt4 book ai didi

Java:修改作为引用传递的参数

转载 作者:行者123 更新时间:2023-11-29 04:45:07 24 4
gpt4 key购买 nike

我必须实现一个具有如下签名的接口(interface)方法:

public int runMethod(final int key, Reference <String> result);

我必须在方法返回之前更新 result 参数的值。例如调用方法时 result 的值为 ABC ,我需要将其修改为 DEF 并返回给调用者。有人可以建议我如何实现它吗?

最佳答案

您不能修改传递给方法的变量。例如:

public int runMethod(final int key, Reference <String> result) {
result = null; // Only changed the method's version of the variable, and not the variable that was passed to the method
}
...
Reference<String> ref = ...
runMethod(0, ref);
// ref is still what you originally assigned it to

但是,您可以修改字段并调用您传递的对象的方法。

public int runMethod(final int key, Reference <String> result) {
result.someField = ...; // Here we are changing the object, which is the same object as what was passed to the method.
}
...
Reference<String> ref = ...
runMethod(0, ref);
// ref.someField has now been changed

另一种方法是将方法的返回类型更改为 Reference<String>并返回更新后的值。

public Reference<String> runMethod(final int key, Reference <String> result) {
return ...;
}
...
Reference<String> ref = ...
ref = runMethod(0, ref);
// ref is now whatever you returned from the method

关于Java:修改作为引用传递的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37505473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com