-1

I'm a beginner in Java and I have a problem with one task.
I'm trying to add an element to ArrayList but there is an exception: Exception in thread "main" java.util.ConcurrentModificationException

    public Anagrams (String path) throws FileNotFoundException {
    List<String> tmpList = new ArrayList<>();

    Scanner scan = new Scanner(new File(path));
    while(scan.hasNext()) {
      tmpList.add(scan.next());
    }
    scan.close();

    tmpList.forEach(word -> {
        if(anList.isEmpty()) {
            ArrayList<String> tmp1 = new ArrayList<String>();
            tmp1.add(word);
            anList.add(tmp1);
        } 
        else {
            anList.forEach(list -> {
                if (isAnagram(word, list.get(0))) {
                    list.add(word);
                } else {
                    ArrayList<String> tmp2 = new ArrayList<String>();
                    tmp2.add(word);
                    anList.add(tmp2);
                }
            });
        }
    });

}

I'm collecting words from a txt file and separate them into different Arrays if they are anagrams or not. I know I can't modify a collection while I'm iterating over it - but I can't figure it out how to avoid this exception.. Please, can you help me?

Ksofiac
  • 382
  • 1
  • 6
  • 21
  • Possible duplicate of [Iterating through a Collection, avoiding ConcurrentModificationException when removing in loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – Morse May 07 '18 at 21:08

1 Answers1

0
anList.forEach(list -> {
            if (isAnagram(word, list.get(0))) {
                list.add(word);
            } else {
                ArrayList<String> tmp2 = new ArrayList<String>();
                tmp2.add(word);
                anList.add(tmp2); // !!
            }
        });

Do you think the forEach call will include elements added to anList on the line that's commented // !!?

Java doesn't know whether or not it should. So it throws.

Figure out how to do something different: add to a different list, for example.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413