无法删除列表元素

cannot delete list elements

我正在Java制造space个入侵者。我试图让激光工作,但每当我移除激光时,计时器(代码所在)就会停止。我不明白这个错误。这是错误:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
    at GraphicsPanel.actionPerformed(GraphicsPanel.java:60)
    at java.desktop/javax.swing.Timer.fireActionPerformed(Timer.java:310)
    at java.desktop/javax.swing.Timer$DoPostEvent.run(Timer.java:242)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:316)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

错误所在的脚本如下:

for(Laser l : lasers) { //the error is on this line
  l.y+=l.dy;
                
  if(l.y < 0)
    lasers.remove(l);

  for(Alien a : aliens) {
    if(l.getHitbox().intersects(a.getHitbox())
      aliens.remove(a);
      lasers.remove(l);
  }

}

有谁知道为什么会这样?如果有必要,我可以发送所有代码。谢谢

Java 不允许在使用 for-each 循环迭代集合时从集合中删除元素。

Javadoc for ConcurrentModificationException

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception

可能的解决方案:

显式使用迭代器

显式使用 Iterator,然后删除您想要的元素。

Iterator<Alien> alienIterator = aliens.iterator();
while (alienIterator.hasNext()){
  Alien alien = alienIterator.next();
  if(laser.getHitbox().intersects(alien.getHitbox()) {
    alienIterator.remove();
    laserIterator.remove();
  }
}

您可以找到其他解决方案here