如何从ArrayList中删除元素? [英] How to remove element from ArrayList?
问题描述
我已将数据添加到 ArrayList
中,现在想要更新该列表并从中删除一些元素.
I have added data into ArrayList
and now want to update that list be deleting some element from it.
我在类型为 CartEntry
的 ArrayList
中有类似 1,2,3,4 的元素.
I have element something like 1,2,3,4 in ArrayList
of type 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));
}
购物车入口代码:
public long getpId() {
return pId;
}
构造函数:
public CartEntry(long pId) {
super();
this.pId = pId;
}
当我尝试这段代码时,它给了我一个错误:
when I am trying this code it gives me an error:
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
这里的 pId 是指定应从项目中删除项目的参数.假设我想删除有 2 个数据的项目,那么我必须做什么?
Here pId is the argument that specify that item should be deleted from items. Suppose I want to delete item that have 2 data then what will I have to do ?
推荐答案
您面临 ConcurrentModificationException
因为您同时对同一个 list
执行两个操作.即循环和删除同一时间.
You are facing ConcurrentModificationException
because you are doing two operations on the same list
at a time. i.e looping and removing same time.
为了避免这种情况,请使用迭代器,它可以保证您安全地从列表中删除元素.
Inorder to avoid this situation use Iterator,which guarantees you to remove the element from list safely .
一个简单的例子看起来像
A simple example looks like
Iterator<CartEntry> it = list.iterator();
while (it.hasNext()) {
if (it.next().getpId() == pId) {
it.remove();
break;
}
}
这篇关于如何从ArrayList中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!