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

时间:2013-05-11 18:08:12

标签: java arrays iterator hashset

当我运行以下代码时,我得到一个例外。我搜索但找不到任何解决方案。

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)

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

}

}

2 个答案:

答案 0 :(得分:17)

该行

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

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

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

答案 1 :(得分:4)

在循环播放add时,您无法呼叫Collection。这里:

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

您可以通过grabLinks内的main方法调用linksList方法:

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

您必须将您的商品添加到另一个Collection,然后将其复制。

让我感到困惑的是,为什么异常来自HashMap,因为我假设linksListList - 显然是这是一个Set。不是世界上最好的名字。

This should help