java 迭代器中我的代码有什么问题

What is wrong with my code in java iterators

我正在写一个文件浏览器

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();

        }

当代码到达 it.remove(); 时,出现以下错误:

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)

引用删除的Docs

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

从文档中引用的有关删除方法的其他信息:

Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next() or previous().

因此,如果您在迭代中调用 add(E),您也不能调用 remove()

我会将 remove() 方法放在 else 语句中:

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

这样调用就不会调用了add(E)

但是,删除方法是 可选的,因为您可以连续调用 next() 方法而不调用 remove()。所以你可以完全省略它,这可能是你想要的结果。

感谢@chancea。

我不得不将我的代码更改为以下几行以实现 BFS 搜索:

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

    }