[英]How can i remove an object from the ArrayList while iterating without getting an “Concurrent Modification Error”
In my project of creating contacts and managing them, when i remove an object from an Array List in a for-loop, a Concurrent Modification Exception is being thrown(as mentioned in javadoc).在我创建联系人和管理联系人的项目中,当我从 for 循环中的数组列表中删除 object 时,会引发并发修改异常(如 javadoc 中所述)。
My question is how can i remove the object without getting "Concurrent Modification Exception"我的问题是如何删除 object 而不会出现“并发修改异常”
I looked at similar posts but couldn't find the answer, some had complex code and many asked why a exception is not thrown.我查看了类似的帖子,但找不到答案,有些人的代码很复杂,很多人问为什么不抛出异常。 This question didn't help me/this specific problem You can read the above link an help me out too(I'm rather new)
这个问题对我没有帮助/这个具体问题你也可以阅读上面的链接来帮助我(我很新)
I am using jdk 14, ide:intelliJ,我正在使用 jdk 14,ide:intelliJ,
I have created methods to manage contacts and get input but I'm only providing the method in which the exception is thrown.我已经创建了管理联系人和获取输入的方法,但我只提供了引发异常的方法。
public class Main {
private static ArrayList<Contact> contacts;
contacts = new ArrayList<>();
private static void deleteContact() {
System.out.println("Please enter contact name: ");
String name = scanner.next();
if (name.equals("")){
System.out.println("Please enter the name");
deleteContact();
}else{
boolean doesExist = false;
for(Contact c:contacts) { //Error pointed on this line.
if (c.getName().equals(name)) {
doesExist = true;
contacts.remove(c);
}
}
if (!doesExist){
System.out.println("There is no such contact");
}
}
showInitialOptions();
}
}
Important code from class 'Contact' class '联系方式'的重要代码
public class Contact {
private String name;
private int number;
private String email;
public Contact(String name, int number, String email ) {
this.name = name;
this.number = number;
this.email = email;
;
}
public String getName() {
return name;
}
}
You can use an Iterator
to iterate over the ArrayList
:您可以使用
Iterator
对ArrayList
进行迭代:
Iterator<Contact> it = contacts.iterator();
while(it.hasNext()){
Contact c = it.next();
if(c.getName().equals(name)){
doesExist = true;
it.remove();
}
}
For your particular problem, Change the line from对于您的特定问题,将行从
for(Contact c:contacts) {
To至
for(int i=contacts.size()-1; i>-1; i--) {
It should work它应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.