如何从ArrayList中删除元素?

Jav*_*s ღ 5 java arraylist

我已经添加了数据ArrayList,现在想要更新该列表,从中删除一些元素.

我有件类似1,2,3,4 ArrayList型的CartEntry.

代码:

ArrayList<CartEntry> items = new ArrayList<CartEntry>();

public void remove(int pId)
{
    System.out.println(items.size());

    for(CartEntry ce : items)
    {
        if(ce.getpId() == pId)
        {
            items.remove(ce);
            //System.out.println(items.get(1));             
        }
    }   
    items.add(new CartEntry(pId));
}
Run Code Online (Sandbox Code Playgroud)

CartEntry代码:

public long getpId() {
    return pId;
}
Run Code Online (Sandbox Code Playgroud)

构造函数:

public CartEntry(long pId) {
    super();
    this.pId = pId;     
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这段代码时,它给了我一个错误:

java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

这里pId是指定应该从项目中删除项目的参数.假设我要删除包含2个数据的项目,那么我将要做什么?

Sur*_*tta 14

你面临的ConcurrentModificationException 是因为你一次只对同一个人进行两次操作list.即循环和删除相同的时间.

为了避免这种情况,请使用Iterator,它可以保证您安全地从列表中删除元素.

一个简单的例子看起来像

Iterator<CartEntry> it = list.iterator();
    while (it.hasNext()) {
        if (it.next().getpId() == pId) {
            it.remove();
            break;
        }
    }
Run Code Online (Sandbox Code Playgroud)