'How to add an item to an arraylist of object via a foreach loop? [closed]

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 1:[1]

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

Solution 2:[2]

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);
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 azro
Solution 2