9

当我运行下面的代码时,我得到一个异常。我搜索但找不到任何解决方案。

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

}

}
4

2 回答 2

19

线

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

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

当您执行增强for循环时,您无法添加到集合中或从集合中移除。

于 2013-05-11T18:12:51.963 回答
5

您不能调用addwhileCollection循环它。这里:

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

您从循环中的方法调用grabLinks方法:mainlinksList

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

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

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

这应该会有所帮助

于 2013-05-11T18:12:33.013 回答