简体   繁体   English

使用迭代器[.next()]时出现ConcurrentModificationException错误

[英]ConcurrentModificationException Error using Iterators [.next()]

I need some help with an iterator that it seems no matter what I do it keeps giving me the error: 我需要一些迭代器的帮助,似乎无论我做什么它一直给我错误:

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
 at java.util.ArrayList$Itr.next(ArrayList.java:831)
 at package.Dictionary.writer(Dictionary.java:72)
 at package.main.main(main.java:24) <5 internal calls>

I could use any help given to help solve this, I am somewhat new to Java programming. 我可以使用任何帮助来帮助解决这个问题,我对Java编程有些新意。 My full code is below: 我的完整代码如下:

package package;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

public class Dictionary {
    Collection<String> webster = new ArrayList<String>();
    Iterator<String> iter = webster.iterator();
    File path = null;

    public Dictionary(Collection<String> words) {
        if (words == null) {
            throw new NullPointerException("Error: Collection NULL");
        } else {
            if (!words.isEmpty()) {
                clear();
            }
        }
    }

    public long load(File file) throws FileNotFoundException {
        String filePath = file.getAbsolutePath();
        if (file.getAbsolutePath().equals(null)
                || file.getAbsolutePath().equals("")) {
            throw new FileNotFoundException("Error: No File Found!");
        } else {
            if (file.exists()) {
                Scanner fileScanner = new Scanner(new File(filePath));
                long time = System.nanoTime();
                while (fileScanner.hasNext()) {
                    webster.add(fileScanner.next());
                }
                long time2 = System.nanoTime();
                long duration = time2 - time;
                return duration;
            } else {
                throw new FileNotFoundException("Error: No File Exsists!");
            }
        }
    }

    public boolean contains(String target) {
        if (webster.contains(target)) {
            return true;
        } else {
            return false;
        }
    }

    public void clear() {
        webster.clear();
    }

    public void writer() throws Exception {
        PrintWriter out = new PrintWriter("words.txt");
        while (iter.hasNext()) {
            out.println(iter.next());
        }
        out.close();
    }
}

The issue you are having now is because you are creating the iterator, then modifying the list by loading the dictionary, then using the iterator (which now throws the exception because the list was modified after the iterator was created). 您现在遇到的问题是因为您正在创建迭代器,然后通过加载字典来修改列表,然后使用迭代器(现在抛出异常,因为在创建迭代器后修改了列表)。

You have your Iterator as an instance variable and you are instantiating it on initialization. 您将Iterator作为实例变量,并在初始化时实例化它。 You don't want to do this here. 你不想在这里这样做。 Instead, create the Iterator in the method you are using it in, eg get rid of the instance variable and do: 相反,在您使用它的方法中创建Iterator ,例如去掉实例变量并执行:

public void writer() throws Exception {
    PrintWriter out = new PrintWriter("words.txt");
    Iterator<String> iter = webster.iterator();
    while (iter.hasNext()) {
        out.println(iter.next());
    }
    out.close();
}

Or, even clearer, and without the use of an explicit Iterator , simply do: 或者,更清楚,并且不使用显式Iterator ,只需:

public void writer() throws Exception {
    PrintWriter out = new PrintWriter("words.txt");
    for (String entry : webster)
        out.println(entry);
    out.close();
}

An iterator is just a temporary object that can be used for iterating over a collection of items, it does not need to stick around. 迭代器只是一个临时对象,可以用于迭代项集合,它不需要留下来。 Create one when you need it, then forget about it when you're done with it. 在需要时创建一个,然后在完成后忘记它。

You are modifying the Collection named webster after the Iterator is created but before it is finished iterating. 在创建Iterator之后但在迭代完成之前,您正在修改名为websterCollection That causes the ConcurrentModificationException . 这会导致ConcurrentModificationException

Considering that you don't need to iterate until you're in writer , just create a local Iterator there, so it won't be there to detect a modification. 考虑到你不需要重复,直到你是writer ,只需要创建一个本地Iterator那里,所以它不会在那里检测到的修改。

PrintWriter out = new PrintWriter("words.txt");
Iterator<String> iter = webster.iterator();
while (iter.hasNext()) {
    out.println(iter.next());
}
out.close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用迭代器时出现ConcurrentModificationException - ConcurrentModificationException when using iterators 与迭代器的ConcurrentModificationException - ConcurrentModificationException with Iterators 使用2个迭代器的java.util.ConcurrentModificationException - java.util.ConcurrentModificationException using 2 iterators 通过列表迭代,同步并使用迭代器时发生ConcurrentModificationException - ConcurrentModificationException on iteration through list, synchronized and using iterators 使用嵌套的迭代器删除没有ConcurrentModificationException的集合项 - Removing collection items without a ConcurrentModificationException using nested Iterators 使用Iterator.next()避免ConcurrentModificationException - Avoid ConcurrentModificationException using Iterator.next() 使用迭代器并删除时出现ConcurrentModificationException错误 - getting ConcurrentModificationException error while using iterator and remove ConcurrentModificationException GL2 / update线程,带有同步和迭代器 - ConcurrentModificationException GL2/update thread, with sync and iterators Java-具有递归方法和嵌套迭代器的ConcurrentModificationException - Java - ConcurrentModificationException with recursive method and nested iterators Java-解析具有2个迭代器和可怕的ConcurrentModificationException的ArrayList - Java - Parsing ArrayList with 2 iterators and the dreaded ConcurrentModificationException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM