gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:33:41 24 4
gpt4 key购买 nike

我正在写一个文件浏览器

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) 就不会被调用

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

关于java - 我在 Java 迭代器中的代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com