且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数组列表中删除对象

更新时间:2023-12-04 20:27:22

原因?

ArrayList 返回的迭代器是 fail-fast 本质上.

Reason?

Iterators returned by ArrayList is fail-fast in nature.

该类的迭代器和listIterator方法返回的迭代器为fail-fast:如果在迭代器创建后的任何时间对列表进行结构修改,在任何除非通过迭代器自己的remove 或add 方法,否则迭代器将抛出一个ConcurrentModificationException.因此,面对并发修改,迭代器会快速而干净地失败,而不是冒着在未来不确定的时间出现任意、非确定性行为的风险.

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.

当我不使用它时,这个迭代器从何而来?

对于集合的增强 for 循环 Iterator 被使用,因此您不能在迭代时调用 remove 方法.

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(); ){   

那么解决方案是什么?

您可以调用 iterator.remove(); 并基于迭代器显式而不是隐式地更改循环.

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());

现在在哪里可以阅读更多信息?

  1. For-Each 循环
  2. ArrayList Java 文档