gpt4 book ai didi

Java编程报错Pass by reference

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

我有一个 Java 应用程序,其中对象引用“Validate.Options”作为参数传递给函数“ValidateResult(Validate.Options option)”并且该函数被称为迭代。在这个基于特定条件的函数中,传递的对象的属性“enableProcessing”被更改,在下一次迭代时不会被重置。如何重置此属性?

下面是示例代码。

public interface Validate 
{
public List validate();


public class Options implements Serializable
{
public String name;
public boolean enableProcessing = true;
public Options(String name)
{
this.name = name;
}
}
}


public class Coder
{
public String name;
public int age;
public Coder(String name, int age)
{
this.name = name;
this.age = age;
}

public void ValidateResult(Validate.Options option)
{
if(option.name.equals(this.name) && option.enableProcessing)
{
option.enableProcessing = false;
//
//business logic and function call
//
}
}

public static void main(String[] args)
{
Validate.Options options = new Validate.Options("Test");
List<Coder> coders = new ArrayList<Coder>();

Coder coder = new Coder("Test", 28);
Coder coder1 = new Coder("XYZ", 18);
Coder coder2 = new Coder("Test", 16);

coders.add(coder);
coders.add(coder1);
coders.add(coder2);

for(Coder co : coders)
{
co.ValidateResult(options);
}
}
}

最佳答案

如果我很好地理解了这个问题 - 在您的 for 循环中,只需添加一行代码来重置您的 public Validate.Options.enableProcessing 字段的值

for(Coder co : coders)
{
//reset options object for the next iteration
options.enableProcessing = true;
co.ValidateResult(options);
}

关于Java编程报错Pass by reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36301181/

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