Iterator的remove()和Collection的remove()

一、遍历集合的方式有很多,这里就以List 为例

如果是单线程的我们一般使用: int  len= list.size()

[java]  view plain  copy
  1. for (int i=0;i<len;i++){  
  2.   
  3. }  

如果是多线程的程序,我们就用Iterator 迭代器来遍历:

[java]  view plain  copy
  1. Iterator<T> it= list.iterator()  
  2. while(it.hasNext()){  
  3. T t= it.next();   //获取集合中的值  
  4. // 这里我们要注意如果直接使用list的remove方法就会报异常  
  5. // 而如果使用Iterator类型的实例的remove方法来删除则不会出现问题  
  6. }  

两种方式,在使用Iterator遍历中如果我们直接使用集合的remove方法来删除则会报异常而如果我们使用Iterator 实例的remove方法来删除的话则正常,这个大家都知道,但为什么?

1、使用Iterator 的remove方法来删除:ArrayList中Iterator 的源码:

[java]  view plain  copy
  1.      
  2.     /** 
  3.      * Returns an iterator over the elements in this list in proper sequence. 
  4.      * 
  5.      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. 
  6.      * 
  7.      * @return an iterator over the elements in this list in proper sequence 
  8.      */  
  9.         // 获取集合的Iterator 实例  
  10.     public Iterator<E> iterator() {  
  11.         return new Itr();  
  12.     }   
  13.   
  14.   /** 
  15.      * An optimized version of AbstractList.Itr 
  16.      */  
  17.     private class Itr implements Iterator<E> {  
  18.         // 表示下一个要访问的元素的索引,从next()方法的具体实现就可看出  
  19.         int cursor;       // index of next element to return  
  20.         // 表示上一个访问的元素的索引  
  21.         int lastRet = -1// index of last element returned; -1 if no such  
  22.         // 表示对ArrayList修改次数的期望值,它的初始值为modCount。  
  23.         int expectedModCount = modCount;  
  24.   
  25.         // 判断这个集合有没有下一个元素的时候,也就是在判断当前值和集合的大小  
  26.         public boolean hasNext() {  
  27.             return cursor != size;  
  28.         }  
  29.         // 获取下一个元素  
  30.         @SuppressWarnings("unchecked")  
  31.         public E next() {  
  32.             checkForComodification();  
  33.             // 表示下一个要访问的元素的索引  
  34.             int i = cursor;  
  35.             // 如果当前位置大于等于集合的大小,则获取下一个值则报异常  
  36.             if (i >= size)  
  37.                 throw new NoSuchElementException();  
  38.             // 将集合的数据复制给新的数组对象  
  39.             Object[] elementData = ArrayList.this.elementData;  
  40.             // arraylist集合底层就是一个数组,如果下一个值得检索值大于 集合的值则 报异常  
  41.             if (i >= elementData.length)  
  42.                 throw new ConcurrentModificationException();  
  43.             //索引值加1   
  44.             cursor = i + 1;  
  45.             // 返回之前的当前值的集合的值  
  46.             return (E) elementData[lastRet = i];  
  47.         }  
  48.          // 删除,使用this 调用类的方法而不是内部类的方法  
  49.         public void remove() {  
  50.             // 如果不满足则抛出异常  
  51.             if (lastRet < 0)  
  52.                 throw new IllegalStateException();  
  53.             // 这个函数的作用就是检测  expectedModCount == modCount是不是相等,如果相等则不会抛出异常否则抛出异常   
  54.             checkForComodification();  
  55.             try {  
  56.                 //删除集合中的内容,删除的是之前的不是现在的  
  57.                 ArrayList.this.remove(lastRet);  
  58.                 cursor = lastRet;  
  59.                 lastRet = -1;  
  60.                 // 使用iterator的方法进行删除的时候会修改expectedModCount的值为modCount 所以这样就不会出现异常  
  61.                 expectedModCount = modCount;  
  62.             } catch (IndexOutOfBoundsException ex) {  
  63.                 throw new ConcurrentModificationException();  
  64.             }  
  65.         }  
  66.         // 这个方法用来检查两个变量的值是否相等  
  67.         final void checkForComodification() {  
  68.             if (modCount != expectedModCount)  
  69.                 throw new ConcurrentModificationException();  
  70.         }  
  71.     }  

2、直接调用集合的remove方法:

[java]  view plain  copy
  1. /** 
  2.      * Removes the first occurrence of the specified element from this list, 
  3.      * if it is present.  If the list does not contain the element, it is 
  4.      * unchanged.  More formally, removes the element with the lowest index 
  5.      * <tt>i</tt> such that 
  6.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> 
  7.      * (if such an element exists).  Returns <tt>true</tt> if this list 
  8.      * contained the specified element (or equivalently, if this list 
  9.      * changed as a result of the call). 
  10.      * 
  11.      * @param o element to be removed from this list, if present 
  12.      * @return <tt>true</tt> if this list contained the specified element 
  13.      */  
  14.     public boolean remove(Object o) {  
  15. // 找到要删除的对象,调用fastRemove() 方法来删除  
  16.  if (o == null) {  
  17.             for (int index = 0; index < size; index++)  
  18.                 if (elementData[index] == null) {  
  19.                     fastRemove(index);  
  20.                     return true;  
  21.                 }  
  22.         } else {  
  23.             for (int index = 0; index < size; index++)  
  24.                 if (o.equals(elementData[index])) {  
  25.                     fastRemove(index);  
  26.                     return true;  
  27.                 }  
  28.         }  
  29.         return false;  
  30.     }  

[java]  view plain  copy
  1.  /* 
  2.     * Private remove method that skips bounds checking and does not 
  3.     * return the value removed. 
  4.     */  
  5.    private void fastRemove(int index) {  
  6.        // modCount的值改变了  
  7.        modCount++;  
  8.        int numMoved = size - index - 1;  
  9.        if (numMoved > 0)  
  10.            System.arraycopy(elementData, index+1, elementData, index,  
  11.                             numMoved);  
  12.       // 删除元素  
  13. elementData[--size] = null// Let gc do its work  
  14.    }  

上面的实例中是Iterator的remove方法和Collection的remove方法,而如果是add方法则也是同样的原理。


通过这两段代码我们发现出现异常的原因:

当集合使用Iterator进行迭代的时候,实际是new Itr()创建一个内部对象初始化包含对象个数,可以理解为在独立线程中操作的。Iterator创建之后引用指向原来的集合对象。当原来的对象数量发生变化时,这个内部对象索引表内容其实是不会同步的。所以,当索引指针往后移动的时候就找不到要迭代的对象了。内部对象操作时为了避免这种情况都会通过checkForComodification方法检测是否一致,不一致提前抛出异常ConcurrentModifiedException。

异常解决办法:
Iterator 支持从源集合中安全地删除对象,只需在 Iterator 上调用 remove() 即可。这样做的好处是可以避免 ConcurrentModifiedException ,这个异常顾名思意:当打开 Iterator 迭代集合时,同时又在对集合进行修改。有些集合不允许在迭代时删除或添加元素,但是调用 Iterator 的 remove() 方法是个安全的做法。

调用Iterator 的remove方法时不仅修改了集合的个数也修改了内部对象的个数,这样再调用checkForComodification() 方法进行检测的时候发现原来集合对象的个数和内部对象的个数相同这样自然就没异常了

总结:

如果调用Iterator 的remove() 方法来删除的话,则iterator的内部对象个数和原来集合中对象的个数会保持同步,而直接调用集合的remove方法来删除的话,集合中对象的个数会变化而Iterator 内部对象的个数不会变化,当调用Iterator 的next 遍历的时候发现集合中的对象的个数和Iterator 内部对象的个数不同,这样指针往后移动的时候就找不到要迭代的对象。这是报异常的主要原因,但 内部对象操作时为了避免这种情况都会通过checkForComodification方法检测是否一致,不一致提前抛出异常ConcurrentModifiedException。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值