-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);
        }
    }
}
alex
  • 8,904
  • 6
  • 49
  • 75

1 Answers1

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • 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. – Votic98 Mar 04 '18 at 19:18