我正在创建一个类调用学生并想将它们存储在列表中我正在使用迭代器从列表中获取元素但是我不能这样做因为发生了异常并且我无法解决这里发生的异常,它如果有人能给我合理的理由,那将是很大的帮助。谢谢
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 类是fail-fast, 这意味着如果在某些线程使用迭代器遍历它时更改 Collection,iterator.next()
将抛出 ConcurrentModificationException。在多线程和单线程 java 编程环境中都可能出现并发修改异常。
在您的示例中,一旦执行 list.add(q);
行,它就会更改迭代器的 modCount
属性。
modCount
提供列表大小更改的次数。 modCount
值用于每个 iterator.next()
调用以检查函数 checkForComodification
() 中的任何修改。
因此它发现 modCount 被更改并抛出 ConcurrentModificationException。
因此,如果您仍想对运行 Iterotir 的列表进行并发修改,您可能需要使用不同的数据结构,如 CopyOnWriteArrayList 代替列表
关于java.util.ConcurrentModificationException 谁能给我解释一下这个的逻辑原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42665527/