zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    day2-元组 列表-赋值和深浅拷贝
    day1-bytes类型 三元运算 进制
    DAY02
    DAY02
    Python格式化、显示颜色
    DAY02
    DAY02
    DAY02
    DAY02
    DAY02
  • 原文地址:https://www.cnblogs.com/iusmile/p/2704076.html
Copyright © 2011-2022 走看看