我正在创造一款游戏,而且它几乎是一种像太空入侵者一样的自上而下的射击游戏。
好吧,我目前正在处理从增强的for循环链接列表中删除实体,而且我们都知道我们不能只是将内容添加到列表中并同时从列表中删除内容。
我一直收到以下错误:
conccurentModificationException
我的问题是如何在不出错的情况下有效地处理链接列表中实体的添加和删除。
这是我的世界级
package game;
import java.awt.Graphics;
import java.util.LinkedList;
import data.Guns;
import entity.Beast;
import entity.Entity;
import entity.Player;
import entity.Projectile;
import external.ImageLoader;
import handlers.Handler;
public class World {
private Player player;
private Handler handler;
// List of all Game Entities
public static LinkedList<Entity> gameFools = new LinkedList<Entity>();
// Constructor for World , this is created once the Game State is instantiated
public World(Handler handler) {
this.handler = handler;
// The player is the first entity added to the list of course
player = new Player(handler, null, Guns.tier1, 64, 64, 400, 900, 500, 5, 0, 0);
gameFools.add(player);
}
public void update() {
// Randomly spawns in a new beast npc
if ((int) (Math.random() * 100) == 0) {
gameFools.add(new Beast(handler,
ImageLoader.loadImage("C:\\Users\\Michael\\workspace\\TopDown\\res\\badguys\\mig1.png"), 32, 32,
(int) (Math.random() * 700 + 50), 50, 10, 1, -1, -1, false, false, false, false, false));
}
//This is the for loop that is used to remove entitys from the linked list
for (Entity e : gameFools) {
// If the object is not within the screen, it gets removed
if (e.getY() <= 0) {
gameFools.remove(e);
}
// Once the Projectiles Range is up, it is removed
if (e.isProjectile()) {
if (((Projectile) e).getRange() <= 0 ) {
gameFools.remove(e);
}
}
e.update();
}
System.out.println("Current Objects entities in game " + gameFools.size());
}
// Getters and Setters
public void render(Graphics g) {
for (Entity e : gameFools) {
e.render(g);
}
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
}