0

I'm trying to iterate an ArrayList and, during this loop, adding more elements to the list. The problem of my code is that isn't working and my first for loop cycles only one time (At first it dirs contains only the root directory).

 for (ListIterator<File> iterator = dirs.listIterator(); iterator.hasNext(); ){
            for (File file : iterator.next().listFiles()) {
                if (checkCondition(file)) {
                    fileList.add(file);
                }
                if (file.isDirectory()) {
                    iterator.add(file);
                }
            }
        }

Where dirs is an ArrayList of files.
I read a lot of answers on stackoverflow (in fact this is a one of them) but non of them seems to work (obviously I'm making some mistakes).

Yes92
  • 301
  • 4
  • 15
  • 2
    You did not post the [exception details](http://idownvotedbecau.se/noexceptiondetails/), and you didn't state what is wrong. However, based on your code I suggest closing this question as possible duplicate of [Concurrent Modification exception](https://stackoverflow.com/questions/1496180/concurrent-modification-exception) – M. le Rutte May 10 '18 at 17:13
  • Is it possible that dirs has only one element? – Thiyagu May 10 '18 at 17:15
  • Yes, at the first iteration it has only the root directory, then I want to loop through its subdirectories, so I tried to add them to the list. – Yes92 May 10 '18 at 17:17
  • Can you check if it really has subdirectories? Maybe add print statement in the second `if` condition – Thiyagu May 10 '18 at 17:21
  • I already did that and yes, it has subdirectories. – Yes92 May 10 '18 at 17:23

1 Answers1

1

If you read the Java Doc for the add(E) method of ListIterator, you will find this:

The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element.

This means that calling next() will not allow you to iterate over the new element.

For different reasons, modifying the list during an iteration should not be done with an iterator or a foreach loop. Maybe you should keep it simple and this should do the trick (assuming dirs is a List object):

    for (int i = 0; i < dirs.size(); i++) {
        List<File> files = dirs.get(i).listFiles();
        for (File file : files) {
            if (checkCondition(file)) {
                fileList.add(file);
            }
            if (file.isDirectory()) {
                dirs.add(file);
            }
        }
    }
Alex C.
  • 166
  • 3
  • 9