java java.util.ConcurrentModificationException 原因

來源:互聯網
上載者:User

用iterator遍曆集合時要注意的地方:不可以對iterator相關的地方做添加或刪除操作。

下面用List為例來說明為什麼會報 ConcurrentModificationException  這個異常,其它集合類似可以自己思考。

 

public static void main(String[] args)
 {
  List<String> set = new ArrayList<String>();
  set.add("a10001");
  set.add("a10002");
  set.add("a10003");
  set.add("a10004");
  set.add("a10005");
  set.add("a10006");
  set.add("a10007");
  
  List<String> del = new ArrayList<String>();
  del.add("a10003");
  del.add("a10004");
  del.add("a10005");
  
  for(String str : set)
  {
   if(del.contains(str))
   {
    set.remove(str);
   }
  }
 }

 

運行這段代碼的結果

 

Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
 at java.util.AbstractList$Itr.next(Unknown Source)
 at com.debug.Debug.main(Debug.java:28)

 

大家都知道for(String str : set) 這句話實際上是用到了集合的iterator() 方法

在iterator的時候是產生了一個List的內部類Itr

JDK源碼

public Iterator<E> iterator() {
   return new Itr();
}

在new Itr()時有一個關鍵性的操作 

/**
  * The modCount value that the iterator believes that the backing
  * List should have.  If this expectation is violated, the iterator
  * has detected concurrent modification.
  */
 int expectedModCount = modCount;

 

再回頭看一下List 的 remove方法

 public boolean remove(Object o) {
 if (o == null) {
            for (int index = 0; index < size; index++)
  if (elementData[index] == null) {
      fastRemove(index);
      return true;
  }
 } else {
     for (int index = 0; index < size; index++)
  if (o.equals(elementData[index])) {
      fastRemove(index);
      return true;
  }
        }
 return false;
    }

 

private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }

 

再看一下 iterator.next()操作

public E next() {
            checkForComodification();
     try {
  E next = get(cursor);
  lastRet = cursor++;
  return next;
     } catch (IndexOutOfBoundsException e) {
  checkForComodification();
  throw new NoSuchElementException();
     }
 }

 

final void checkForComodification() {
     if (modCount != expectedModCount)
  throw new ConcurrentModificationException();
 }

 

相信看到這兒大家已經應該明白了為什麼會出現在這個異常了。

總結:

  iterator 時 將expectedModCount = modCount 在remove()時 modCount++ 在next()時

 if (modCount != expectedModCount)
  throw new ConcurrentModificationException();

 

一旦刪除或添加元素後 modCount ,expectedModCount 這兩個值就會不一致 當next時就會報ConcurrentModificationException

 

瞭解了原由,解決方案就很簡單了 在遍曆時用一個集合存放要刪除的對象 在遍曆完後 調用removeAll(Collection<?> c) 就OK了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.