Java 如何从ArrayList中删除元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20116710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove element from ArrayList?
提问by Java Curious ?
I have added data into ArrayList
and now want to update that list be deleting some element from it.
我已将数据添加到其中ArrayList
,现在想要更新该列表,即从中删除一些元素。
I have element something like 1,2,3,4 in ArrayList
of type CartEntry
.
我有类似 1,2,3,4ArrayList
类型的元素CartEntry
。
Code :
代码 :
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));
}
CartEntry Code :
购物车输入代码:
public long getpId() {
return pId;
}
Constructor :
构造函数:
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)
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 ?
这里 pId 是指定应从项目中删除项目的参数。假设我想删除具有 2 个数据的项目,那么我必须做什么?
采纳答案by Suresh Atta
You are facing ConcurrentModificationException
because you are doing two operations on the same list
at a time. i.e looping and removing same time.
您正在面对,ConcurrentModificationException
因为您同时在执行两个操作list
。即循环和删除同一时间。
Inorder to avoid this situation use Iterator,which guarantees you to remove the element from list safely .
为了避免这种情况,请使用 Iterator,它可以保证您安全地从列表中删除元素。
A simple example looks like
一个简单的例子看起来像
Iterator<CartEntry> it = list.iterator();
while (it.hasNext()) {
if (it.next().getpId() == pId) {
it.remove();
break;
}
}
回答by Shaun
Implement .equals in CartEntry and then use ArrayList.remove(CartEntry) or loop through your array list, find the item with some condition, mark the index, and call ArrayList.remove(index) -- AFTER the loop
在 CartEntry 中实现 .equals,然后使用 ArrayList.remove(CartEntry) 或循环遍历数组列表,找到具有某些条件的项目,标记索引,然后调用 ArrayList.remove(index) -- 在循环之后
回答by Joachim Sauer
There are at least two problems with your code:
您的代码至少有两个问题:
you call
remove
on the collection you iterate over, that will cause aConcurrentModificationException
if you continue iterating after theremove
.There are two ways to fix this:
- stop iterating after you found the object you want to remove (just add a
break
or areturn
) or - switch from the enhanced for-loop to using an
Iterator
and itsremove
method.
- stop iterating after you found the object you want to remove (just add a
you addan element in your
remove
method, that's probably not what you want.
您调用
remove
您迭代的集合,ConcurrentModificationException
如果您在remove
.有两种方法可以解决这个问题:
- 找到要删除的对象后停止迭代(只需添加 a
break
或 areturn
)或 - 从增强的for循环切换到使用一个
Iterator
和它的remove
方法。
- 找到要删除的对象后停止迭代(只需添加 a
您在方法中添加了一个元素
remove
,这可能不是您想要的。
So I'd use this code (this assumes that there is only ever one CartEntry
with a given id in the list):
所以我会使用这个代码(假设CartEntry
列表中只有一个具有给定 id 的代码):
public void remove(int pId)
{
for(CartEntry ce : items)
{
if(ce.getpId() == pId)
{
items.remove(ce);
return;
}
}
}
If the assumption with the unique id is not correct, then you'll need to use the Iterator
approach:
如果具有唯一 id 的假设不正确,那么您需要使用以下Iterator
方法:
public void remove(int pId)
{
Iterator<CartEntry> it = items.iterator();
while(it.hasNext())
{
CartEntry ce = it.next();
if(ce.getpId() == pId)
{
it.remove();
}
}
}
回答by Masudul
Try,
尝试,
public void remove(int pId){
Iterator<CartEntry> it = items.iterator();
while(it.hasNext()) {
CartEntry entry = it.next();
if (entry.getpId() == pId) {
it.remove();
}
}
}
回答by Sage
The enhanced-for
(or for each) loop for iterating over an Expression
which is a subtype of Iterable<E>
or raw Iterable
, basically equivalent to the following form:
enhanced-for
用于迭代 an的(或 for each)循环,Expression
它是Iterable<E>
或 raw的子类型Iterable
,基本上等同于以下形式:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableIdentifiers_opt TargetType Identifier = (TargetType) #i.next();
Statement
}
This is clearly stated in jls 14.14.2. The enhanced for statementsection.
这在jls 14.14.2 中有明确说明。增强的语句部分。
For your context the Expression
is an ArrayList
. the iterators returned by ArrayList
's iterator method is fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException
.
对于您的上下文,它Expression
是一个ArrayList
. 的迭代ArrayList
器方法返回的迭代器是快速失败的:如果在迭代器创建后的任何时间以任何方式修改列表的结构,除了通过迭代器自己的 remove 或 add 方法,迭代器将抛出一个ConcurrentModificationException
.
use an Iterator
instead and use it's own remove()
method:
改用 anIterator
并使用它自己的remove()
方法:
Iterator<E>iterator = list.iterator();
while(iterator.hasNext())
if(iterator.next().equals(E))
iterator.remove();
回答by ashwini
you have created an Arraylist of type carEntry
. So you need to create an Iterator of type CarEntry
您已经创建了一个 Arraylist 类型carEntry
。所以你需要创建一个 Iterator 类型CarEntry
Iterator<CarEntry> it = items.iterator();
while(it.hasNext())
{
if(it.next().getPId == PId)
it.remove();
}