Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element from ArrayList?

Tags:

java

arraylist

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 ?

like image 973
Java Curious ღ Avatar asked Nov 21 '13 09:11

Java Curious ღ


People also ask

Can you remove element from ArrayList?

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.

How does remove work in ArrayList?

The remove() method is used to remove an element at a specified index from ArrayList. Shifts any subsequent elements to the left (subtracts one from their indices). The index of the element to be removed.

How do you remove multiple elements from an ArrayList in Java?

Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How does remove () work in Java?

Return values of remove() in JavaThe remove method returns true if an object passed as a parameter is removed from the list. Otherwise, it returns false. The remove method returns the removed element if an index is passed. It throws IndexOutOfBoundsException if the specified index is not in range.


3 Answers

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;
        }
    }
like image 94
Suresh Atta Avatar answered Sep 28 '22 00:09

Suresh Atta


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.

    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
    • switch from the enhanced for-loop to using an Iterator and its remove method.
  2. you add an element in your remove method, that's probably not what you want.

So I'd use this code (this assumes that there is only ever one CartEntry with a given id in the list):

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:

public void remove(int pId)
{
    Iterator<CartEntry> it = items.iterator();
    while(it.hasNext())
    {
        CartEntry ce = it.next();
        if(ce.getpId() == pId)
        {
            it.remove();
        }
    }   
}
like image 37
Joachim Sauer Avatar answered Sep 27 '22 22:09

Joachim Sauer


you have created an Arraylist of type carEntry. So you need to create an Iterator of type CarEntry

Iterator<CarEntry> it =  items.iterator();    
while(it.hasNext())
{
   if(it.next().getPId == PId)
   it.remove();
}
like image 29
ashwini Avatar answered Sep 28 '22 00:09

ashwini