gpt4 book ai didi

Java对象数组相互覆盖

转载 作者:行者123 更新时间:2023-12-02 08:30:21 24 4
gpt4 key购买 nike

我有三个类 MainProcessEmployee。我的问题是,最后一个对象数组总是覆盖第一个。我认为逻辑上没有问题,我只是简单地使用getters和setters。

    public class Main {

public static void main(String args[]){
Process p = new Process();

p.setEmployeeList(p.generate());

p.setExternalEmployeeList(p.generate());

for(int i=0; i<5; i++){
System.out.println(p.getEmployeeList()[i].getID());
}

System.out.println();

for(int i=0; i<5; i++){
System.out.println(p.getExternalEmployeeList()[i].getID());
}

}

}

--

import java.util.Random;

public class Process {

private int rndTemp;
private int numberOfDice = 5;
private Random random = new Random();
public Employee[] employeeList = new Employee[5];
public Employee[] externalEmployeeList = new Employee[5];
private Employee[] tempList = new Employee[5];

public Employee[] generate(){
for(int i=0; i<numberOfDice; i++){
rndTemp = random.nextInt((6 - 1) + 1) + 1;
Employee emp = new Employee(rndTemp);

tempList[i] = emp;
}
return tempList;

}

public Employee[] getEmployeeList(){
return employeeList;

}

public Employee[] getExternalEmployeeList(){
return externalEmployeeList;

}

public void setExternalEmployeeList(Employee[] externalEmployeeList){
this.externalEmployeeList = externalEmployeeList;
}

public void setEmployeeList(Employee[] employeeList){
this.employeeList = employeeList;
}

}

--

public class Employee {

public int empID;

public Employee(int empID) {
this.empID = empID;
}


public void setID(int empID) {
this.empID = empID;
}

public int getID() {
return empID;
}
}

最佳答案

你必须把

Employee[] tempList = new Employee[5];

在您的生成方法中,它将按预期工作。

否则,您将只传递对数组的引用,而下一次您将覆盖同一个数组。

此外,其他两个数组不需要初始化,因为它们将被分配给新创建的数组。

关于Java对象数组相互覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27561902/

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