Removing an object from a arraylist

只谈情不闲聊 提交于 2019-12-24 05:09:33

问题


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


回答1:


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



回答2:


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.




回答3:


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".



来源:https://stackoverflow.com/questions/13101279/removing-an-object-from-a-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!