![](/img/trans.png)
[英]Java - Getting common element from two ArrayLists of different data type
[英]Java: removing two objects simultaniously from different ArrayLists
我有对象Bullet,我同时将它们添加到两个ArrayList中,下面简要介绍了这些列表。 完成某些操作后,我希望从两个列表中删除一个项目符号。 这种方法正确吗? 我不断收到错误:java.util.ConcurrentModificationException
或者,您是否可以想到以比ArrayList更好的解决方案来以这种方式处理对象?
//there are ArrayList<Bullet> bullets and ArrayList<Updatable> updatable, in the class
public void removeBullet(Bullet bullet) {
for (ListIterator<Bullet> bulletIterator = bullets.listIterator(); bulletIterator.hasNext();) {
Bullet tempBullet = bulletIterator.next();
if (tempBullet.equals(bullet)) {
for (ListIterator<Updatable> updatableIterator = updatable.listIterator(); updatableIterator.hasNext();) {
Updatable tempUpdatable = updatableIterator.next();
if (tempUpdatable.equals(bullet)) {
updatableIterator.remove();
bulletIterator.remove();
return;
}
}
}
}
}
编辑:问题的根源是我在列表之一上使用了一个迭代器,恰好同时在另一个地方,因此出现了错误。 对于可更新列表,此代码工作正常。
发生ConcurrentModificationException的原因是,您试图从Iterator中删除项目符号,而您同时也在for循环中进行迭代; java不喜欢您执行此操作,并且会抛出异常。
要解决此问题,您必须遍历两个Iterators并分别将其删除,或者如rdonuk所述,只需使用ArrayList remove()
方法,如果您尝试删除不在列表中的内容,则不会抛出任何异常。数组列表; 如果删除了该对象,它将返回true
,否则返回false
,因此您甚至不必首先检查要删除的对象是否包含在ArrayList中。
只需使用ArrayList
remove方法。
bullets.remove(bullet);
和
updatable.remove(bullet);
编辑:
移除ArrayList
使用的迭代器的方法:
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
如您所见,它已经使用ArrayList.remove()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.