java.util.ConcurrentModificationException异常解决方法

今天在调试一段代码的时候,抛出异常 java.util.ConcurrentModificationException,这个异常之前没怎么碰到过,

抛错代码如下:

private List<String> getShopLinkList(Elements elements) throws Exception {
        List<String> shopUrlList = new ArrayList<String>();
        
for(Element element :elements){
            String parseLink = element.attr("href") ;
            boolean isShopUrl = isShopUrl(parseLink);
            if (!isShopUrl) {
                elements.remove(element);
                continue;
            }
            shopUrlList.add(parseLink);
        }
        return removeDuplicateUrl(shopUrlList);
    }

debug代码跟踪,发现第一次循环执行了elements.remove(element);  这段代码,循环第二次的异常抛了异常。

解决方法:

private List<String> getShopLinkList(Elements elements) throws Exception {
        List<String> shopUrlList = new ArrayList<String>();
        Iterator<Element> iterator = elements.iterator() ;
        
        while(iterator.hasNext()) {
            Element element = iterator.next() ;
            String parseLink = element.attr("href") ;
            boolean isShopUrl = isShopUrl(parseLink);
            if (!isShopUrl) {
                iterator.remove() ;//这段代码很重要
                elements.remove(element);
                continue;
            }
            shopUrlList.add(parseLink);
        }
        return removeDuplicateUrl(shopUrlList);
    }
原文地址:https://www.cnblogs.com/iusmile/p/2704076.html