-2

So im currently testing ArrayList and with the code below, im always getting a java.util.ConcurrentModificationException at line 23. I read the documentation and it states

it is not generally permissible for one thread to modify a Collection while another thread is iterating over it

but im not modifying the collection while iterating over it, im doing it beforehand, so im not sure what im doing wrong here.

public class Test {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> a = new ArrayList<String>();
        ListIterator<String> lt = a.listIterator();
        System.out.print("Enter a word: ");
        String s = scanner.nextLine();

        while (!s.equals("")) {
            a.add(s);
            System.out.print("Enter another word: ");
            s = scanner.nextLine();
        }

        while (lt.hasNext()) {
            String z = lt.next(); // line 23
            System.out.println(z);
        }
    }
}
1
  • Please search before asking as this sort of question has been asked many times previously. You need to modify the list with the iterator Commented Mar 4, 2018 at 19:01

1 Answer 1

2

But you are, you have created the iterator before a loop that adds to the ArrayList. Move the creation of the iterator to after the first loop.

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

1 Comment

Ok thanks, that works. I thought i might create the iterator whenever i want, as long as im not actively using or iterating with it. But i was wrong with that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.