首页 > 解决方案 > Java 循环遍历 arraylist 并使用匹配的代码删除 item 类型的任何对象

问题描述

我正在尝试执行遍历 item 类型对象的数组列表的任务。每个项目对象都有一个代码变量。如果已经有一个带有代码的对象,那么它将从列表中删除。

代码:

//Search list for item based on code. 
//If item with code is found, it is removed/deleted from the list. 
//Else user is told "No item Found"

public void deleteItem(String code)
{
    boolean found = false;

    for(Item item : items)
    {
        if(item.getCode().equals(code))
        {
            found = true;
            items.remove(item);
        }
    }

    if(found)
    {
        System.out.println("Found and removed item with code: " + code);          
    }
    else
    {
       System.out.println("No item with code" + code + "found");
    }
}

我得到 java.util.ConcurrentModificationException

请问有什么帮助吗?

标签: javafor-looparraylist

解决方案


推荐阅读