Issue
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
You have created the list of Employee once ArrayList<Employee> sampleList= new ArrayList<>();
and adding it to all the teams, the same instance, each team share the exact same list, so when adding to one, you see it in each
You need to create a new list for each Team
List<Teams> TeamsList = new ArrayList<>();
for (Employee employee : employeesList) {
Teams team = new Teams(employee.firstName, new ArrayList<>());
TeamsList.add(team);
}
Also as class Teams
represent one team, it should be named Team
at singular
Answered By - azro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.