How to remove element from ArrayList?

arraylist, java

Solution

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

Problem

I have added data into `ArrayList` and now want to update that list be deleting some element from it. 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 : ``` 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 ?

Original source