简体   繁体   English

如何从ArrayList中删除元素?

[英]How to remove element from ArrayList?

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 . 我在CartEntry类型的ArrayList中有类似1,2,3,4的元素。

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 : CartEntry代码:

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. 这里pId是指定应该从项目中删除项目的参数。 Suppose I want to delete item that have 2 data then what will I have to do ? 假设我要删除包含2个数据的项目,那么我将要做什么?

You are facing ConcurrentModificationException because you are doing two operations on the same list at a time. 您正面临ConcurrentModificationException因为您一次在同一list上执行两个操作。 ie looping and removing same time. 即循环和删除相同的时间。

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;
        }
    }

There are at least two problems with your code: 您的代码至少有两个问题:

  1. you call remove on the collection you iterate over, that will cause a ConcurrentModificationException if you continue iterating after the remove . 你叫remove您遍历集合,这将导致ConcurrentModificationException ,如果你继续在迭代后remove

    There are two ways to fix this: 有两种方法可以解决这个问题:

    • stop iterating after you found the object you want to remove (just add a break or a return ) or 找到要删除的对象后停止迭代(只需添加breakreturn
    • switch from the enhanced for-loop to using an Iterator and its remove method . 从增强的for循环切换到使用Iterator 及其remove方法
  2. you add an element in your remove method, that's probably not what you want. 你在remove方法中添加一个元素,这可能不是你想要的。

So I'd use this code (this assumes that there is only ever one CartEntry with a given id in the list): 所以我会使用这段代码(这假设在列表中只有一个具有给定id的CartEntry ):

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();
        }
    }   
}

you have created an Arraylist of type carEntry . 你已经创建了一个carEntry类型的Arraylist。 So you need to create an Iterator of type CarEntry 所以你需要创建一个CarEntry类型的迭代器

Iterator<CarEntry> it =  items.iterator();    
while(it.hasNext())
{
   if(it.next().getPId == PId)
   it.remove();
}

在CartEntry中实现.equals然后使用ArrayList.remove(CartEntry)或循环遍历数组列表,找到具有某些条件的项,标记索引,并调用ArrayList.remove(index) - 循环之后

Try, 尝试,

public void remove(int pId){

Iterator<CartEntry> it = items.iterator();

 while(it.hasNext()) {
    CartEntry entry = it.next();
    if (entry.getpId() == pId) {
        it.remove();
    }
  }
}

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: 迭代于Iterable<E>或raw Iterable的子类型的Expressionenhanced-for (或for each循环),基本等效于以下形式:

  for (I #i = Expression.iterator(); #i.hasNext(); ) {   
      VariableIdentifiers_opt TargetType Identifier = (TargetType) #i.next();
         Statement
   }

This is clearly stated in jls 14.14.2. 这在jls 14.14.2中有明确说明 The enhanced for statement section. 增强的for语句部分。

For your context the Expression is an ArrayList . 对于您的上下文, Expression是一个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 . ArrayList的迭代器方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候对列表进行结构修改,除了通过迭代器自己的remove或add方法之外,迭代器将抛出ConcurrentModificationException

use an Iterator instead and use it's own remove() method: 使用Iterator代替并使用它自己的remove()方法:

  Iterator<E>iterator = list.iterator();
  while(iterator.hasNext())
    if(iterator.next().equals(E))
      iterator.remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM