Reputation: 129
I have and array where I create few swords on the tiled map and when i step on them they need to be deleted but when I step on them game chrashes.
at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source)
MY CODE:
I guess the loop is looking for the object even if its deleted?
private List<Sword> swords = new ArrayList<Sword>();
I create them one time:
public GameRender(GameWorld world, int gameHeight) {
for (int i = 0; i<100 ; i++ ) {
swords.add(new Sword());
}
When i step on it:
for (Sword sword : swords) {
if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
&& playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
sword.pickMe();
swords.remove(sword);
}
}
There is other loop in render():
for (Sword sword : swords) {
sword.createMe();
}
I dont think you need to see the Sword class. If you do i'll put it in here. How do i fix it so I dont get the error?
Upvotes: 0
Views: 103
Reputation: 81588
for (Sword sword : swords) {
if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
&& playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
sword.pickMe();
swords.remove(sword); //this line throws ConcurrentModificationException
}
}
Due to how the enhanced for
loop works, you either need to use an Iterator<Sword>
to remove it:
Iterator<Sword> iterator = swords.iterator();
while(iterator.hasNext())
{
Sword sword = iterator.next();
if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
&& playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
sword.pickMe();
iterator.remove();
}
}
Or the following:
for (int i = 0; i < swords.size(); i++) {
Sword sword = swords.get(i);
if(playery+7>=sword.position.y && playery+7<=sword.position.y+tilesize
&& playerx+7>=sword.position.x &&playerx+7<=sword.position.x+tilesize) {
sword.pickMe();
swords.remove(i--);
}
}
Upvotes: 3