0
private static void deleteContact() {
    System.out.println("Please enter the name:");
    String name = scanner.next();
    if (name.equals("")) {
        System.out.println("!Please enter the name");
        deleteContact();
    } else {
        boolean doesExist = false;

        // line 182
        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }

        if (!doesExist) {
            System.out.println("There is no such contact");
        }
    }

    showInitialOptions();
}
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    at java.util.ArrayList$Itr.next(ArrayList.java:859)
    at org.neutral_networks.javaChallange.Main.deleteContact(Main.java:182)

line 182 in my code mean, this for loop:

        for (Contact c: contacts) {
            if (c.getName().equals(name)) {
                doesExist = true;
                contacts.remove(c);
            }
        }

Please help me out to solve this exception.

i just build this deleteContact() method for remove contact from the contact list.

i am getting the input from the user and this is actually name of the contact which one users would like to remove from the contact list.

so, generally when i call the function and and give input it will causes the exit my program and say,, Exception in thread "main" java.util.ConcurrentModificationException

  • If there will be only a single `Contact` instance to remove, you can put a `break` statement after `contacts.remove(c);` call, but not that `remove()` does additional iteration to find the element to remove. Therefore, a better alternative would be to use Java 8 method `removeIf()` or `Iterator.remove()`, and by the way both these options can handle the case when there would be several contacts to remove. – Alexander Ivanchenko Dec 31 '22 at 19:18
  • yea, i am try to remove or delete just single contact instance. and it's working when i just adding `break` statement. thank you so much @alexander-ivanchenko – Mr. Zahangir Alam Jan 01 '23 at 01:49

0 Answers0