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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:15:06  来源:igfitidea点击:

How to remove element from ArrayList?

javaarraylist

提问by Java Curious ?

I have added data into ArrayListand now want to update that list be deleting some element from it.

我已将数据添加到其中ArrayList,现在想要更新该列表,即从中删除一些元素。

I have element something like 1,2,3,4 in ArrayListof 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 ConcurrentModificationExceptionbecause you are doing two operations on the same listat 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:

您的代码至少有两个问题:

  1. you call removeon the collection you iterate over, that will cause a ConcurrentModificationExceptionif you continue iterating after the remove.

    There are two ways to fix this:

    • stop iterating after you found the object you want to remove (just add a breakor a return) or
    • switch from the enhanced for-loop to using an Iteratorand its removemethod.
  2. you addan element in your removemethod, that's probably not what you want.

  1. 您调用remove您迭代的集合,ConcurrentModificationException如果您在remove.

    有两种方法可以解决这个问题:

  2. 您在方法中添加了一个元素remove,这可能不是您想要的。

So I'd use this code (this assumes that there is only ever one CartEntrywith 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 Iteratorapproach:

如果具有唯一 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 Expressionwhich 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 Expressionis 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 Iteratorinstead 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();
}