![](/img/trans.png)
[英]Reason Behind the java.util.ConcurrentModificationException
[英]java.util.ConcurrentModificationException Can someone explain me the logical reason for this
我正在創建一個類調用學生,並希望將這些存儲在列表中我使用迭代器從列表中獲取元素但我不能這樣做,因為發生異常,我無法解決這里發生的異常,這將是偉大的如果有人能給我合理的理由,請幫忙。謝謝
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;
}
}
}
Java Collection類是快速失敗的,這意味着如果在某個線程使用迭代器遍歷它時將更改Collection,則iterator.next()
將拋出ConcurrentModificationException。 在多線程以及單線程java編程環境中可以出現並發修改異常。
這里在你的例子中一行list.add(q);
是執行它更改迭代器的modCount
屬性。
modCount
提供列表大小已更改的次數。 modCount
值在每個iterator.next()
調用中使用,以檢查函數checkForComodification
()中的任何修改。
因此,它發現要更改的modCount會拋出ConcurrentModificationException。
因此,如果您仍希望對運行Iterotir的List進行並發修改,則可能需要使用不同的數據結構(如CopyOnWriteArrayList)來代替List
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.