Search code examples
javaloopsarraylistlistiterator

Java Adding items to ArrayList while iterating it


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).


Solution

  • 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);
                }
            }
        }