• 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);
        }
  • 相关阅读:
    java基础-代理模式
    java基础-反射(细节)
    java基础-反射
    设计模式之单例
    23种设计模式汇总整理
    dialog--not attached to window manager
    java之设计模式
    android-sdk和api版本
    studio之mac快捷键
    控件之ReleLayout属性
  • 原文地址:https://www.cnblogs.com/iusmile/p/2704076.html
Copyright © 2020-2023  润新知