首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异常ConcurrentModificationException

异常ConcurrentModificationException
EN

Stack Overflow用户
提问于 2021-01-16 19:07:52
回答 1查看 15关注 0票数 0

我想模拟一个简单的电话应用程序,它可以管理联系人和处理消息。我已经为我的manageContacts函数创建了一个函数,我称之为delteContact。

然而,当我尝试删除我的联系人时,我得到了这个错误,我检查了我的代码,我不明白为什么它会抛出这个错误?

代码语言:javascript
复制
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();
    }

有没有人能帮帮我,我哪里搞错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-16 19:29:06

代码语言:javascript
复制
for(Contact c : contacts){
            if(c.getName().equals(name)){
                doesExist = true;
                contacts.remove(c);

您正在修改增强的for循环中的集合-通常这是不允许的,因为它是由拒绝此行为的迭代器隐式控制的。迭代器正在抛出异常。

您可以通过显式声明迭代器并要求迭代器为您删除元素来解决此问题:

代码语言:javascript
复制
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
                }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65748959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档