-2

Hi I'm trying to create an Address Book and store all entries to an arrayList. I;m currently having a problem deleting a item from the list. Can someone please help me. Here is my ArrayList which contains my setter/getter and constructor

List<AddressBook> addToList = new ArrayList<AddressBook>();

This my code for removing the item from the list :

public class DeleteEntry {
    Scanner scanner = new Scanner(System.in);

    public void deleteEntry(List<AddressBook> addToList){
        System.out.println(" Please input name to delete: ");
        String name = scanner.next();
         for (AddressBook item : addToList) {
            if (name.equalsIgnoreCase(item.getName())){
                addToList.remove(item);
                System.out.println("Item removed");
            }else {
                System.out.println("name not found");
            }
        }
    }

The error that I'm getting is

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
    at addressbook.jedi.DeleteEntry.deleteEntry(DeleteEntry.java:12)
    at addressbook.jedi.MainAddressBook.main(MainAddressBook.java:29)

line 12 is

for (AddressBook item : addToList) {
Rustam
  • 6,485
  • 1
  • 25
  • 25
Onedaynerd
  • 49
  • 2
  • 9

1 Answers1

0

Use the old for with iterator and invoke the iterator.remove() method instead of invoking the remove inside a for each loop

for (Iterator<AddressBook> it = addToList.iterator(); it.hasNext();) {
    AddressBoook item = it.next();
    if (name.equalsIgnoreCase(item.getName())){
        it.remove();
        System.out.println("Item removed");
    } else {
        System.out.println("name not found");
    }
}

ArrayList iterator is fail-fast, meaning that any change in the collection done after you obtained the iterator from it will cause a ConcurrentModificationException when accessing the next element. The iterator.remove() method bypass that limitation.

Claudio
  • 1,848
  • 12
  • 26