如何通过 foreach 循环将项目添加到对象的数组列表中?

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

我有一个团队 class 是这样的:(构造函数)

public Teams(String managerName, ArrayList<Employee> directReportEmployees){
    this.managerName = managerName;
    this.directReportEmployees = directReportEmployees;
}

我的目标是将一名员工添加到经理为 'John' 的团队列表中。为此,我遍历团队列表以找到经理名称为 'John' 的团队,然后将一名员工添加到经理名称为 'John'.

的员工列表中
for (Teams team : TeamsList) {
    if (team.managerName.equals("John")){
        team.directReportEmployees.add(emp1);
       //assume emp1 is an object type Employee.
    }
}

团队数组列表就是这样生成的。

        ArrayList<Employee> sampleList= new ArrayList<>();
        ArrayList<Teams> TeamsList = new ArrayList<>();

        for (Employee employee : employeesList) {
            Teams team = new Teams(employee.firstName, sampleList);
            TeamsList.add(team);
        }

但是,当我这样做时,这会将员工添加到所有团队中。我不确定我哪里错了。

非常感谢任何帮助。

您已经创建了一次员工列表ArrayList<Employee> sampleList= new ArrayList<>();并将其添加到所有团队,相同实例,每个团队共享完全相同的列表,所以当添加到一个,你在每个

中看到它

您需要为每个团队创建一个新列表

List<Teams> TeamsList = new ArrayList<>();

for (Employee employee : employeesList) {
    Teams team = new Teams(employee.firstName, new ArrayList<>());
    TeamsList.add(team);
}

又如class Teams代表一个队,单数

时应命名为Team

因此,当您使用相同的 ArrayList 实例化团队数组时,就会发生这种情况。

您没有提供完整的代码,但我假设这是您当前的代码

ArrayList<Employee> sampleList= new ArrayList<>();
    ArrayList<Teams> TeamsList = new ArrayList<>();

    for (Employee employee : employeesList) {
        Teams team = new Teams(employee.firstName, sampleList);
        TeamsList.add(team);
    }

将其更改为

    ArrayList<Teams> TeamsList = new ArrayList<>();

    for (Employee employee : employeesList) {
        Teams team = new Teams(employee.firstName, new ArrayList<>());
        TeamsList.add(team);
    }