解决List的ConcurrentModificationException的几种方法

 

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Test {

	public static void main(String[] args) {
		String codes = "HH|140402001>RQSPF=1+SPF=3,140402002>RQSPF=3+SPF=1|2*1";
		Pattern p = Pattern.compile("(\\d{9})");
        Matcher m = p.matcher(codes);
		Map<String, String> rqMap = new HashMap<String, String>();
		List<String> itemList = new ArrayList<String>();
		
		CopyOnWriteArrayList<String> currList = new CopyOnWriteArrayList<String>(itemList);
    //    List<String> currList = Collections.synchronizedList(itemList);     //报ConcurrentModificationException异常
		
		
        while (m.find()) {
    //    	System.out.println(m.group());
        	itemList.add(matcher.group());
        }
		
		
				
		for (String yhItem : currList) {	//正确
			String totalItem = xml.getStringValue("row[" + i + "].@close");
			if (yhItem.equals(mid)) {
				rqMap.put(yhItem, totalItem);
				currList.remove(yhItem);
			}
		}
			
//			for (int j=0; j<itemList.size(); j++) {   //正确	//或者使用 list.iterator 的remove() 或者使用CopyOnWriteArrayList,使用其它的方式可能会报ConcurrentModificationException异常
//				String totalItem = xml.getStringValue("row[" + i + "].@close");
//				String yhItem = itemList.get(j);
//				if (yhItem.equals(mid)) {
//					rqMap.put(yhItem, totalItem);
//					itemList.remove(j);
//				}
//			}
		
		
//        Iterator<String> iterator = itemList.iterator();    	//正确
//        while (iterator.hasNext()) { 
//		    String totalItem = xml.getStringValue("row[" + i + "].@close");
//            String yhItem = iterator.next();  
//			if (yhItem.equals(mid)) {
//				rqMap.put(yhItem, totalItem);
//				iterator.remove();
//			}
//        }   
				
		
//			for (String yhItem : itemList) {		//报ConcurrentModificationException异常
//				String totalItem = xml.getStringValue("row[" + i + "].@close");
//				if (yhItem.equals(mid)) {
//					rqMap.put(yhItem, totalItem);
//					int k = itemList.indexOf(yhItem);
//					itemList.remove(k);
//				}
//			}

	}

}

 

 

 详细源代码分析及原理摘自其它的博客:

http://arron-li.iteye.com/blog/645008

http://blog.csdn.net/aa4790139/article/details/6438869

http://www.cnblogs.com/yanghuahui/p/3365509.html

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值