I have been at this for a while now, and can't figure out how to delete from an Arraylist.
This is my delete method:
static List<AddressInfo> contacts = new ArrayList<>();
private static void deleteContact() {
//get name of contact to delete
System.out.println("Which contact would you like to delete?");
System.out.println("Enter the contacts first name:");
String nameToFind = scanner.nextLine();
//loop through array list to find name that matches entry
int matches = 0;
for(AddressInfo person : contacts) {
if(person.getName().equals(nameToFind)) {
contacts.remove(person);
matches++;
}
}
if(matches<=0) {
System.out.println("There are no contacts found with this name.\n");
}
showMainMenu();
}
And here is my a snippet of my AddressInfo class if required:
AddressInfo(String name, String surname, String phoneNumber, String email) {
this.name = name;
this.surname = surname;
this.phoneNumber = phoneNumber;
this.email = email;
id++;
}
String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
There are getter and setter methods for name, surname, phoneNumber, and email.
Question: My delete method does not work. I thought calling the .remove
would remove that contact that I searched for? I have found other questions, and have tried everything suggested, but I can't get the delete to work. I have add, edit, find, and display methods that are working great. Any help is appreciated!
edit
This is the error exception that is displayed (using NetBeans)
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 addressbook.AddressBook.deleteContact(AddressBook.java:106)
at addressbook.AddressBook.showMainMenu(AddressBook.java:203)
at addressbook.AddressBook.addContact(AddressBook.java:95)
at addressbook.AddressBook.showMainMenu(AddressBook.java:200)
at addressbook.AddressBook.main(AddressBook.java:17)
C:\Users\Andre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 10 seconds)