线程“main”中的异常 java.util.ConcurrentModificationException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16500240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:10:51  来源:igfitidea点击:

Exception in thread "main" java.util.ConcurrentModificationException

javaarraysiteratorhashset

提问by Isuru

When I run the below code, I get an exception. I searched but couldn't find any solution.

当我运行以下代码时,出现异常。我搜索但找不到任何解决方案。

Exception in thread "main" java.util.ConcurrentModificationException
     at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
     at java.util.HashMap$KeyIterator.next(Unknown Source)
     at com.aybits.software.linkgrabber.Grabber.main(Grabber.java:45)

Line number 45 is for(String linkFromCollection : linksList){

第 45 行是for(String linkFromCollection : linksList){

public class Grabber {

static String url;
Document doc;
static Set<String> linksList = new HashSet<String>();
String matchingString ="java2s.com/Code";
static boolean isCrawling = true;
static int STOP_WATCH = 0;

public Grabber(String url){
    Grabber.url = url;
}

public void grabLinks(String urlToCrawl) throws IOException{
    doc = Jsoup.connect(urlToCrawl).timeout(20 * 1000).get();
    Elements links = doc.select("a[href]");

    for (Element link : links) {
        //print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
        if(link.attr("abs:href").toString().contains(matchingString)){
            if(!linksList.contains(link.attr("abs:href").toString())){
                System.out.println("Added - " + link.attr("abs:href"));
                linksList.add(link.attr("abs:href").toString());
            }
        }
    }
}

public static void main(String[] args) throws IOException {
    Grabber app = new Grabber("http://java2s.com");
    app.grabLinks(url);

    while(isCrawling){
        for(String linkFromCollection : linksList){
            app.grabLinks(linkFromCollection);

            if(linksList.contains(linkFromCollection)){
                STOP_WATCH += 5;
                System.out.println("STOP_WATCH IS " + STOP_WATCH);
            }else{
                STOP_WATCH -= 1;
                System.out.println("STOP_WATCH IS " + STOP_WATCH);
            }

            if(STOP_WATCH >= 100){
                isCrawling = false;
                System.out.println("STOP_WATCH IS " + STOP_WATCH);
            }
        }


    }
    ICVSWrite writer = new ICVSWrite();

    String[] strArray = (String[]) linksList.toArray();
    writer.write(strArray);

}

}

采纳答案by Eric Jablow

The line

线

linksList.add(link.attr("abs:href").toString());

modifies the linksListcollection while you are iterating over it. The next time through the forloop in main, Java calls nexton the collection, sees that the collection has been modified, and throws the exception.

linksList迭代时修改集合。下一次通过 中的for循环时main,Java 调用next该集合,看到该集合已被修改,并抛出异常。

When you are doing an enhanced forloop, you cannot add to or remove from the collection.

当您进行增强for循环时,您无法在集合中添加或删除。

回答by Boris the Spider

You cannot call addon a Collectionwhile looping over it. Here:

你不能在它上面循环调用add一段Collection时间。这里:

for (Element link : links) {        
    if(...){
        if(...){
            ...
            linksList.add(link.attr("abs:href").toString());
                      ^^^ <- here
        }
    }
}

You call grabLinksmethod from your mainmethod from within a loop over linksList:

grabLinksmain循环中的方法中调用方法linksList

for(String linkFromCollection : linksList) {
   app.grabLinks(linkFromCollection);       

You have to add your items to another Collectionand then copy them over after.

您必须将您的项目添加到另一个项目Collection,然后再复制它们。

What had me puzzled for a little while was why the exception was coming from a HashMapas I had assumed that linksListwas a List- obviouslyit's a Set. Not the best name in the world.

让我困惑了一会儿的是为什么异常来自 a ,HashMap因为我认为这linksList是 a List-显然它是Set. 不是世界上最好的名字。

This should help.

这应该会有所帮助