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);  
  }  
4
  • Can you please also show us where op1 and op2 are defined? Commented Mar 11, 2017 at 15:27
  • just updated the content Commented Mar 11, 2017 at 15:32
  • This needs more data: stack exception. The code showed has iterators over empty lists. hasNext() will never return true. Commented Mar 11, 2017 at 22:23
  • Possible duplicate of Ways to iterate over a List in java? Commented Mar 11, 2017 at 22:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.