Chris Headleand
Chris Headleand

Reputation: 6193

Removing an object from a arraylist

I have an arraylist with names, phone numbers and locations.

I would like to remove certain items from that array if possible

Is there anyway to remove the item once I have found it like I have tried below?

public void delete(String nameToDelete) 
{    
    for (Entry entry : Directory.entries) { 
        if (entry.name.equalsIgnoreCase(nameToDelete))
        {
            //remove(entry);
        }
    }
}

Thanks

Upvotes: 2

Views: 258

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213223

You should use Iterator to remove the entry from your list. If you try to modify your List while iterating it through enhanced for-loop, it may throw a ConcurrentModificationException, although this does not happen always, but there is not guarantee.

Here's how you can use Iterator for your List: -

Iterator<Entry> iterator = Directory.entries.iterator();

while (iterator.hasNext()) {
    Entry entry = iterator.next();

    if (entry.name.equalsIgnoreCase(nameToDelete)) {
        iterator.remove();
    }
}

Even in the Iterator you should remove the element using the iterator.remove method and not with the list.remove method, because that will not make a difference.

You can also use ListIterator which gives you even more operations and methods to iterate the list. See the documentation for details.

To use ListIterator, you can create it like this: -

ListIterator<Entry> listIterator = Directory.entries.listIterator();

And rest of the code works the same way.

Upvotes: 1

Amit Deshpande
Amit Deshpande

Reputation: 19185

Reason?

Iterators returned by ArrayList is fail-fast in nature.

The iterators returned by this class's iterator and listIterator methods are 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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Where does this iterator Come from while I am not using it?

For enhanced for loop for collections Iterator gets used so you can not call remove method while you are iterating.

So your loop is same as below

for (Iterator<Entry> i = c.iterator(); i.hasNext(); ){   

What is the Solution Then ?

You can call iterator.remove(); and change loop based on iterator explicitly rather than implicitly.

    String inputWord = "john";
    ArrayList<String> wordlist = new ArrayList<String>();
    wordlist.add("rambo");
    wordlist.add("john");
    for (ListIterator<String> iterator = wordlist.listIterator(); iterator
            .hasNext();) {
        String z = iterator.next();
        if (z.equals(inputWord)) {
            iterator.remove();
        }
    }
    System.out.println(wordlist.size());

Now Where Can I Read more?

  1. The For-Each Loop
  2. ArrayList Java docs

Upvotes: 2

asteri
asteri

Reputation: 11572

What you would do is use if entry.getKey().equals(nameToDelete) to check if it's the one you want, then use the remove() method to remove that entry.

However you cannot do this inside of a for() loop iterating over the same collection you're modifying. You will get a ConcurrentModificationException.

See "How to Avoid ConcurrentModificationException when using an Iterator".

Upvotes: 0

Related Questions