2017-03-08 75 views
1

我正在創建一個類調用學生,並希望將它們存儲在列表中我正在使用迭代器從列表中獲取元素,但我不能這樣做,因爲一個異常正在發生的事情,我不能化解這是這裏發生了異常,這將是很大的幫助,如果有人可以給我this.Thank邏輯原因,你java.util.ConcurrentModificationException有人可以解釋我的這種邏輯原因

import java.awt.List; 
    import java.util.ArrayList; 
    import java.util.Collection; 
    import java.util.Iterator; 
    import java.util.Vector; 
    import java.util.List.*; 

    public class Runs { 

     /** 
     * @param args 
     */ 
     public static void main(String[] args) { 
      // TODO Auto-generated method stub 

      try { 

       // adding student class to list 
       java.util.List list = new ArrayList<Student>(); 
       Student q = new Student("hello", 1); 
       Iterator<Student> l = list.iterator(); 
       list.add(q); 
       // error false in this segment of the code 
       Student op = l.next(); 
       String hhh = op.getnamez(); 
       System.out.println(hhh); 
       System.out.println(op.getnamez()); 

      } catch (Exception e) { 
       System.out.println("" + e); 

      } 

     } 

     public static class Student { 
      // student class 
      public String name; 
      private int age; 

      public Student(String s, int a) { 

       this.name = s; 
       this.age = a; 

      } 

      public String getnamez() { 
       return this.name; 

      } 

     } 

    } 
+1

可能的複製集合,避免ConcurrentModificationException當在循環中刪除](http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Jeremy

回答

0

是招行 迭代L = list.iterator( ); list.add(q);

您不能檢索一個迭代事後修改列表

你應該改變的代碼以及以更好地反映您遍歷List中,但是這將解決您的錯誤。

+0

謝謝@LordUkthar,它得到了修復:) –

2

Java集合類是快速失敗,這意味着,如果該系列將同時一些線程使用迭代器遍歷在它被改變,iterator.next()將拋出ConcurrentModificationException。併發修改異常可以用於多線程以及單線程Java編程環境。

在你的例子中,一旦行list.add(q);被執行,它會改變迭代器的modCount屬性。

modCount提供了列表大小已被更改的次數。 modCount值用於每個iterator.next()調用以檢查函數checkForComodification()中的任何修改。

因此,它發現要更改的modCount,它會引發ConcurrentModificationException。

所以,如果你想還是做併發修改到你的列表上正在運行的Iterotir你可能需要的地方清單堅持像的CopyOnWriteArrayList不同的數據結構[通過迭代的

+0

正確。雖然它也可能出現在多線程程序中,但在幾乎所有我見過的情況下(這裏都是如此),它對於簡單的單線程程序來說是一個問題。例外名稱中的* Concurrent *可能會讓一些人感到困惑。 – Kayaman

+0

非常感謝您的解釋mr @mhasan !!!我真的明白在該代碼段發生了什麼。謝謝再次:) –