I have a Team class something like this: (Constructor)
public Teams(String managerName, ArrayList<Employee> directReportEmployees){
this.managerName = managerName;
this.directReportEmployees = directReportEmployees;
}
My goal here is to add an employee to a list of team whose manager is ‘John’. To do this, I am looping through the list of teams to find the team with the manager name ‘John’ and then adding an employee to the list of employees with the manager ‘John’.
for (Teams team : TeamsList) {
if (team.managerName.equals("John")){
team.directReportEmployees.add(emp1);
//assume emp1 is an object type Employee.
}
}
This is how the arraylist of teams was generated.
ArrayList<Employee> sampleList= new ArrayList<>();
ArrayList<Teams> TeamsList = new ArrayList<>();
for (Employee employee : employeesList) {
Teams team = new Teams(employee.firstName, sampleList);
TeamsList.add(team);
}
However, when I do this, this adds the employee to all of the teams. I am not sure where I am going wrong.
Any help is much appreciated.
>Solution :
So, this happens when you instantiate your teams array with the same ArrayList.
You have not provided full code, But im assuming this is your current code
ArrayList<Employee> sampleList= new ArrayList<>();
ArrayList<Teams> TeamsList = new ArrayList<>();
for (Employee employee : employeesList) {
Teams team = new Teams(employee.firstName, sampleList);
TeamsList.add(team);
}
change that to
ArrayList<Teams> TeamsList = new ArrayList<>();
for (Employee employee : employeesList) {
Teams team = new Teams(employee.firstName, new ArrayList<>());
TeamsList.add(team);
}