使用foreach并删除如果一起使用,它将导致correntModificationException



我有三个类

 (With getters and Setters)
Student (Class)
   String studentName;
   int sid;
   List<Employee>
Employee (Class)
   String employeeName;
   int eid;
   List<Admin>
Admin (Class)
   String name;
   int adminId;
public class Testing {
public static void main(String arfs[]) {
    Admin admin = new Admin();
    Admin admin2 = new Admin();
    Employee employee = new Employee();
    Student student = new Student();
    List<Admin> adminList = new ArrayList<Admin>();
    List<Employee> empList = new ArrayList<>();
    admin.setName("AdminOne");
    admin.setAdminId(1);
    adminList.add(admin);
    admin2.setName("AdminTwo");
    admin2.setAdminId(2);
    adminList.add(admin2);
    employee.setEmployeeName("employeeOne");
    employee.setEid(4);
    employee.setAdmin(adminList);
    System.out.println("EMPLOYEE: "+employee.getAdmin());
    empList.add(employee);
    student.setStudentName("studentOne");
    student.setSid(9);
    student.setEmployee(empList);
    student.getEmployee().forEach(s -> {
        if(s.getEid()==4) {
            s.getAdmin().removeIf(p -> p.getName().equals("AdminTwo"));
        }
    });
    System.out.println("Student Name: "+student.getStudentName()+" EMP: "+student.getEmployee());

}
}

我在没有任何例外的情况下获取输出,但是我想知道是否有机会从上述代码中获得" conturrentModification exception" ...

当我们迭代收集并进行修改时,我们将获得并发修改例外...

不可能用 foreach oreach 或 contrentModificationException 或 ,因为也无法修改列表。

在您的情况下,您会迭代雇员,但是您修改了管理员。

相关内容

  • 没有找到相关文章

最新更新