gpt4 book ai didi

java - forEach和RemoveIf一起使用会导致ConcurrentModificationException吗?

转载 作者:行者123 更新时间:2023-12-02 02:11:16 26 4
gpt4 key购买 nike

我有三门课

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


}
}

我得到的输出没有任何异常,但我想知道是否有机会从上面的代码中获取“ConcurrentModificationException”...

当我们迭代一个集合并在其中进行修改时,我们会得到并发修改异常...

最佳答案

使用 forEachenchanced for 不可能得到 ConcurrentModificationException,因为也不可能修改列表。

在您的情况下,您迭代employeeList,但修改adminList。

关于java - forEach和RemoveIf一起使用会导致ConcurrentModificationException吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57326074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com