Reputation: 3
I wanted to simulate a simple phone application, that can manage contacts and handle messages. I have created a function for my manageContacts Function, that I called delteContact.
However when I try to delete my contact I got this error, I checked my code and I don't see why it would trow that error?
private static void deleteContact() {
System.out.println("Bitte den Namen eingeben:");
String name = scanner.next();
if(name.equals("")){
System.out.println("Bitte den Namen eingeben:");
deleteContact();
}else{
boolean doesExist = false;
for(Contact c : contacts){
if(c.getName().equals(name)){
doesExist = true;
contacts.remove(c);
}
}
if(!doesExist){
System.out.println("Dieser Kontakt existiert nicht.");
}
}
showInitialOptions();
}
Can someone help me where I did here a mistake?
Upvotes: 0
Views: 19
Reputation: 11620
for(Contact c : contacts){
if(c.getName().equals(name)){
doesExist = true;
contacts.remove(c);
You are modifying a collection inside an enhanced for loop - typically this is not allowed because it is implicitly controlled by an Iterator that rejects this behaviour. The Iterator is throwing the Exception.
You can get around this by explicitly declaring an iterator, and asking the iterator to remove the element for you:
Iterator<Contact> i = contacts.iterator();
while(i.hasNext()){
Contact c = i.next(); //you must call next() before remove()
if(c.getName().equals(name)){
doesExist = true;
i.remove(); //call remove on the iterator, not the collection
}
Upvotes: 1