我们都知道你不能这样做:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
Run Code Online (Sandbox Code Playgroud)
ConcurrentModificationException等等......这显然有时起作用,但并非总是如此.这是一些特定的代码:
public static void main(String[] args) {
Collection<Integer> l = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
l.add(4);
l.add(5);
l.add(6);
}
for (int i : l) {
if (i == 5) {
l.remove(i);
}
}
System.out.println(l);
}
Run Code Online (Sandbox Code Playgroud)
当然,这会导致:
Exception in thread "main" java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)
...即使多线程没有这样做......无论如何.
什么是这个问题的最佳解决方案?如何在循环中从集合中删除项而不抛出此异常?
我也在Collection这里使用任意,不一定是ArrayList,所以你不能依赖get.
for (String fruit : list)
{
if("banane".equals(fruit))
list.remove(fruit);
System.out.println(fruit);
}
Run Code Online (Sandbox Code Playgroud)
这里有一个带删除指令的循环.在执行时,我在控制台输出下面得到一些ConcurrentModificationException:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
at Boucle.main(Boucle.java:14)
abricot
banane
Run Code Online (Sandbox Code Playgroud)
问题:如何用循环删除一些元素?
我有一个foreach循环遍历向量中的每个对象.当我调试代码时,它成功运行向量中的第一个对象.但是当它试图为第二个对象运行循环时它会失败.我确信矢量中有多个元素.
for(Object shape : vecForShapes)
{
currentNode = (Drawable) shape;
newNode = getResources().getDrawable(R.drawable.nodered);
newNode.setBounds(currentNode.getBounds());
vecForShapes.remove(currentNode);
vecForShapes.add(newNode);
}
Run Code Online (Sandbox Code Playgroud)
基本上我的问题是,为什么这个循环失败了?我真的不明白这里有什么问题.
PS我的最终目标是currentNode从矢量中删除,newNode然后替换它,然后在我的onDraw方法中重绘整个矢量.
谢谢