Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an item to an arraylist of object via a foreach loop?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        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);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading