A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 颜春 中级黑马   /  2013-2-27 21:23  /  1755 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

ArrayList<String> list = new ArrayList<String>();
                  list.add("123");
                  list.add("456");
                  list.add("789");
                  list.add("963");
                  int i=0;
                  for ( String st : list) {  
                       
                      if (st.equals("123")) {  
                             
                          list.remove(st);
                     }  
                      System.out.println(list.get(i)+ " ");  
                      i++;
                  }
为什么会报java.util.ConcurrentModificationException  异常   求解

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

4 个回复

倒序浏览
并发修改异常
ArrayList是不同步的.这与在迭代中操作add一样,你在用list取出方法,你同时又在里面改他的元素,导致他不知道自己现在有多少个要出取了.
回复 使用道具 举报
这个异常是说,你不能在对一个List进行遍历的时候将其中的元素删除掉
  1.            ArrayList<String> list = new ArrayList<String>();
  2.                   list.add("123");
  3.                   list.add("456");
  4.                   list.add("789");
  5.                   list.add("963");
  6.                   int i=0;
  7.                   for ( String st : list) {  
  8.                        
  9.                       if (st.equals("123")) {  //你这个循环是在遍历list集合,但是遍历过程中又要删除里面的元素,所以就报错了
  10.                              
  11.                           list.remove(st);
  12.                      }  
  13.                       System.out.println(list.get(i)+ " ");  
  14.                       i++;
复制代码
你可以定义一个集合来收集要删除的字符串,等遍历完后再进行删除
  1.            ArrayList<String> list = new ArrayList<String>();
  2.                    ArrayList<String> Dellist = new ArrayList<String>();//在这里定义个集合,用于收集你要删除的元素,等遍历结束后再对收集的元素删除

  3.                   list.add("123");
  4.                   list.add("456");
  5.                   list.add("789");
  6.                   list.add("963");
  7.                
  8.                                   int i = 0;
  9.                
  10.                   for ( String st : list) {  
  11.                        
  12.                       if (st.equals("123")) {
  13.                           Dellist.add(st);   
  14.                          i++;
  15.                      }
  16.                                          }
  17.                                           list.removeAll(Dellist);  //这里用removeAll,是因为不确定要删除的集合里的元素有多少个!
  18.                       System.out.println(list.get(i)+ " ");
复制代码

评分

参与人数 1技术分 +1 收起 理由
Rancho_Gump + 1

查看全部评分

回复 使用道具 举报
集合迭代过程中如果要对集合本身做添加,删除等操作。请不要用普通的遍历方式,而应使用Iterator迭代器来操作。
回复 使用道具 举报
可否理解为问题的根源在ArrayList是动态数组造成的计数混乱?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马