Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

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

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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
                }
                

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...