0

I have problem in doing looping for iteration. It kept throwing ConcurrentModificationException whenever I try to make a loop. What I'm trying to do is displaying input data from database in JFreeChart GUI. I've been working for hours doing this. I saw some question almost similar but mine differs is displaying from MySQL Database

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);  
  }  
Amirul Idzham
  • 43
  • 1
  • 10

1 Answers1

1

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(); and 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), e.g. ensuring exclusive access to the lists while you are modifying and iterating them.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Thanks it works! What I did make changes to my code is modifying the position of iterator and removing the public static modifier. I think I understand a bit how Iterator works – Amirul Idzham Mar 12 '17 at 00:53