我正在尝试使用foreach从ArrayList中删除SubClass类型的项目,并在找到它时将其删除.
代码:
for (SuperClass item : list)
{
if (item instanceof SubClass)
{
list.remove(item);
}
}
Run Code Online (Sandbox Code Playgroud)
我真的不知道迭代器在这种情况下是如何工作的,但我要问的是:这样安全吗?或者它应该抛出一个超出范围的例外?
任何帮助表示赞赏!
你不能list使用foreach语句删除一段时间的项目.你会得到ConcurrentModificationException
你需要使用Iterator.remove()方法
for(Iterator<SuperClass> i = list.iterator(); i.hasNext(); ) {
SuperClass s = i.next();
if(s instanceof SubClass) {
i.remove();
}
}
Run Code Online (Sandbox Code Playgroud)