我有三个课程Main
,Process
和Employee
。我的问题是,最后一个对象数组总是覆盖第一个对象数组。我不认为逻辑存在问题,我只是使用getter和setter。
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;
}
}
答案 0 :(得分:5)
你必须把
Employee[] tempList = new Employee[5];
在您的generate方法中,它将按预期工作。
否则你只会传递对数组的引用,下次你将覆盖同一个数组。
此外,其他两个数组不需要初始化,因为它们将被分配新创建的数组。
答案 1 :(得分:1)
问题是tempList
应该是局部变量而不是类变量。