简体   繁体   中英

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).

My question is how can i remove the object without getting "Concurrent Modification Exception"

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,

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'

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<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM