简体   繁体   English

循环迭代器Java抛出ConcurrentModificationException

[英]Looping Iterator Java throw ConcurrentModificationException

I have problem in doing looping for iteration. 我在循环迭代时遇到问题。 It kept throwing ConcurrentModificationException whenever I try to make a loop. 每当我尝试进行循环时,它都会不断抛出ConcurrentModificationException。 What I'm trying to do is displaying input data from database in JFreeChart GUI. 我想做的是在JFreeChart GUI中显示来自数据库的输入数据。 I've been working for hours doing this. 我已经工作了几个小时了。 I saw some question almost similar but mine differs is displaying from MySQL Database 我看到了一些几乎相似的问题,但与MySQL数据库显示的却不同

Here's is some of my codes: 这是我的一些代码:

    public static ArrayList<String> s  = new <String> ArrayList() ;
    public static ArrayList<Double> d  = new <Double> ArrayList() ;
    public static Iterator op1 = s.iterator();
    public static Iterator op2 = d.iterator();

DefaultCategoryDataset dataset = new DefaultCategoryDataset( );
    while(op1.hasNext()){
    Object a= op1.next();
    Object b= op2.next();
    String c = (String) a;
    double d = (double) a;
    dataset.addValue(d , speed , c);  
  }  

Don't put your iterators in (static) fields. 不要将迭代器放在(静态)字段中。

As it stands, the iterators are created before you put anything into the lists; 就目前而言,迭代器是在您将任何内容放入列表之前创建的; so those iterators will fail after you put anything into the lists. 因此,在将任何内容放入列表后,这些迭代器都会失败。

The following simply recreates this: 以下只是重新创建了此内容:

List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
list.add("");
it.next(); // Concurrent modification exception

You don't get the same problem if the iterator is created after the add. 如果在添加之后创建迭代器,您不会遇到相同的问题。 Try reversing the Iterator<String> it = list.iterator(); 尝试反转Iterator<String> it = list.iterator(); and list.add(""); list.add(""); lines to see this. 线看到这一点。

Basically, the iterators are invalidated when any structural changes (like adding or removing elements) occur. 基本上,当发生任何结构更改(例如添加或删除元素)时,迭代器将无效。

Create the iterators in the method containing the loop, immediately before the loop. 在循环之前,在包含循环的方法中创建迭代器。

DefaultCategoryDataset dataset = new DefaultCategoryDataset( );   
Iterator<String> op1 = s.iterator(); // Don't use raw types.
// Same for other iterator.
while(op1.hasNext()){
  String c = op1.next();

You may also need to take steps to avoid genuinely concurrent modification (modification by a different thread during iteration), eg ensuring exclusive access to the lists while you are modifying and iterating them. 您可能还需要采取措施避免真正的并发修改(在迭代过程中由其他线程进行修改),例如,确保在修改和迭代列表时对列表具有独占访问权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM