What's wrong with my code in java iterators

I am writing a file explorer

ArrayList<File> folders = new ArrayList<File>(Arrays.asList(parent
                .listFiles(filter)));

ListIterator<File> it = folders.listIterator();

        while (it.hasNext()) {

            File file = it.next();

            if (file.isDirectory())
            {
                ArrayList<File> subFolders = new ArrayList<File>(
                        Arrays.asList(file
                                .listFiles(filter)));
                for (File sub : subFolders) {
                    it.add(sub);
                }
            }
            else
            {
                mediaFiles.add(file);
            }

            it.remove();

        }

When the code reaches it.remove();, I get the following error:

02-04 23:32:47.670: E/AndroidRuntime(20230):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-04 23:32:47.670: E/AndroidRuntime(20230):    at dalvik.system.NativeStart.main(Native Method)
02-04 23:32:47.670: E/AndroidRuntime(20230): Caused by: java.util.ConcurrentModificationException
02-04 23:32:47.670: E/AndroidRuntime(20230):    at java.util.AbstractList$SimpleListIterator.remove(AbstractList.java:71)
+4
source share
2 answers

Thanks @chancea.

I had to change my code to the following lines to implement a BFS search:

    Queue<File> queue = new LinkedList<File>();
    queue.add(parent);

    ArrayList<File> mediaFiles = new ArrayList<File>();

    while (!queue.isEmpty()) {
        File file = queue.remove();

        if (file.isDirectory())
        {
            ArrayList<File> subFolders = new ArrayList<File>(
                    Arrays.asList(file
                            .listFiles(filter)));
            for (File sub : subFolders) {
                queue.add(sub);
            }
        }
        else
        {
            mediaFiles.add(file);
        }

    }
0
source

Quoting Docs Removal:

Removes the last item from the list that was returned by the next () or previous () (optional operation). This call can only be made once per call before the next or previous. This can only be done if add (E) has not been called since the last call to the next or previous .

, :

, remove() set (Object) ; , next() previous().

, add(E) , remove().

remove() else:

else
{
    mediaFiles.add(file);
    it.remove();
}

, , add(E)

, next(), remove(). , , .

+9

All Articles