[英]Exception ConcurrentModificationException
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.
我为我的 manageContacts Function 创建了一个 function,我称之为 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?有人可以帮我在这里做错了吗?
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.您正在增强的 for 循环内修改集合 - 通常这是不允许的,因为它由拒绝此行为的 Iterator 隐式控制。 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.