`

解决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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics