1

I have three classes

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


}
}

I am getting the output without any exceptions, but i would like to know is there any chance of getting "ConcurrentModificationException" from the above code...

When we iterate a collection and make modification in the same, we will get concurrent modification exception...

JavaLearner1
  • 607
  • 2
  • 8
  • 21
  • 4
    *When we iterate a collection and make modification in the same, we will get concurrent modification exception*: but that's not what you're doing. You're iterating on the employee list, and you remove from the admin list, a **different** collection. Note: your code is very hard to read for a simple, stupid reason: you don't respect the rules of English. student.getEmployee() should be named student.getEmployees(), with an s, because there are several employees: it returns a list of employees, not an Employee. – JB Nizet Aug 02 '19 at 12:01
  • @JBNizet Iterating from Student --> get Employee --> getAdmin.removeIf(), since we are not iterating the admin List...no possibility of ConcurrentModificationException?... – JavaLearner1 Aug 02 '19 at 12:04
  • No, since you're rmoving from a different collection from the one you're iterating. – JB Nizet Aug 02 '19 at 12:05

1 Answers1

0

It is impossible to get ConcurrentModificationException with forEach or enchanced for because it is impossible also to modify the list.

In your case you iterate employeeList, but you modify adminList.

Dorin Simion
  • 131
  • 5