使用Iterator 或for-each注意:java.util.ConcurrentModificationException
Posted on 2010-03-02 12:22 Fingki.li 阅读(1360) 评论(1) 编辑 收藏 所属分类: About development
在使用Iterator处理Collection时,注意java.util.ConcurrentModificationException。
1.如果你仅仅是对collection进行遍历查询,那么不必担心什么。
2.但如果你在遍历过程中要对collection进行删除,那么你就要注意了。
For example:
privatevoidtestDel(){
(用for-each遍历也会出个类似问题)
具体原因是可以看一下 先看看List中的remove方法源码:
1.如果你仅仅是对collection进行遍历查询,那么不必担心什么。
2.但如果你在遍历过程中要对collection进行删除,那么你就要注意了。
For example:
privatevoidtestDel(){
- List<String>list=newArrayList<String>();
- for(inti=0;i<10;i++){
- Stringstr="td"+i;
- list.add(str);
- }
- for(Iteratorit=list.iterator();it.hasNext();){
- Stringstr=(String)it.next();
- if(str.equals("td5")){
- //list.remove(str);// 删除方法一
- it.remove();// 删除方法二
- }
- }
- }
(用for-each遍历也会出个类似问题)
具体原因是可以看一下 先看看List中的remove方法源码:
- publicbooleanremove(Objecto){
- if(o==null){
- for(intindex=0;index<size;index++)
- if(elementData[index]==null){
- fastRemove(index);
- returntrue;
- }
- }else{
- for(intindex=0;index<size;index++)
- if(o.equals(elementData[index])){
- fastRemove(index);
- returntrue;
- }
- }
- returnfalse;
- }
- privatevoidfastRemove(intindex){
- modCount++;//特别注意这里,这里只增加了modCount的值
- intnumMoved=size-index-1;
- if(numMoved>0)
- System.arraycopy(elementData,index+1,elementData,index,
- numMoved);
- elementData[--size]=null;//Letgcdoitswork
- }
- publicEnext(){
- checkForComodification();
- try{
- Enext=get(cursor);
- lastRet=cursor++;
- returnnext;
- }catch(IndexOutOfBoundsExceptione){
- checkForComodification();
- thrownewNoSuchElementException();
- }
- }
- finalvoidcheckForComodification(){ //注意这个方法
- if(modCount!=expectedModCount) //检查这两个值是否相同
- thrownewConcurrentModificationException();
- }
- publicvoidremove(){
- if(lastRet==-1)
- thrownewIllegalStateException();
- checkForComodification();
- try{
- AbstractList.this.remove(lastRet);
- if(lastRet<cursor)
- cursor--;
- lastRet=-1;
- expectedModCount=modCount;//设置expectedModCount
- }catch(IndexOutOfBoundsExceptione){
- thrownewConcurrentModificationException();
- }
- }
- finalvoidcheckForComodification(){
- if(modCount!=expectedModCount)
- thrownewConcurrentModificationException();
- }