如何从ArrayList中删除元素? [英] How to remove element from ArrayList?

查看:156
本文介绍了如何从ArrayList中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经加入数据转换成的ArrayList 现在要更新列表中,从它删除某些内容。

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

我在的ArrayList 类型 CartEntry 元素类似1,2,3,4。

I have element something like 1,2,3,4 in ArrayList of type 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:

CartEntry Code :

public long getpId() {
    return pId;
}

构造器:

public CartEntry(long pId) {
    super();
    this.pId = pId;     
}

当我尝试这个code它给了我一个错误:

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的,因为你是在同一个名单上做两个操作在一个时间。即循环和除去同一时间。

You are facing ConcurrentModificationException because you are doing two operations on the same list at a time. i.e looping and removing same time.

中序,以避免这种情况下使用Iterator,它保证你安全地从列表中删除的元素。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆