我已经向 ArrayList
中添加了数据,现在想通过删除其中的一些元素来更新该列表。
我在类型为 CartEntry
的 ArrayList
中拥有类似 1、2、3、4 的元素。
代码:
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));
}
购物车项目代码:
public long getpId() {
return pId;
}
构造函数:
public CartEntry(long pId) {
super();
this.pId = pId;
}
当我尝试运行这段代码时,它会报错:
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
这里的pId是指定要从items中删除的项的参数。假设我想要删除具有2个数据的项目,我该怎么做?