I have a problem while going through this iterator loop, in which i go through each element of this.env, but within this list, wanting to remove a different element of said list. When I try to remove any item of said iterating list, I receive this error: java.util.ConcurrentModificationException, and as far as I understand this is caused due to modifying the iterating list without using iterator.remove().
Code:
public void envActions(IOHandler ioHandler, PlayerClass player){
Iterator<WorldElement> worldElementIterator = this.env.iterator();
while(worldElementIterator.hasNext()){
WorldElement worldElement = worldElementIterator.next();
//for(WorldElement worldElement:this.env){
if(worldElement instanceof EntityClass){
EntityClass entity=(EntityClass) worldElement;
if(entity.nature.contains("hostile")){
MonsterClass mEntity=(MonsterClass) entity;
if(!(mEntity.attacks.size()*(Math.random()+0.25)>=mEntity.attacks.size())){
Double followerNum = (Math.random()*player.followers.size());
Integer followerNumInt=followerNum.intValue();
if(followerNumInt<2){
PlayerClass target=player;
Double attacknumD=mEntity.attacks.size()*Math.random();
Integer attacknum= attacknumD.intValue();
Integer playerarmor=player.getArmorValue();
int enemydamage=mEntity.attacks.get(attacknum).getDamage()*(1-(playerarmor/1000));
target.health=target.health-enemydamage;
ioHandler.printToConsole("\nThe "+mEntity.name+" attacked you with "+mEntity.attacks.get(attacknum).getAttack()+" and did "+mEntity.attacks.get(attacknum).getDamage()+" damage! you have "+player.health+" health left!");
} else {
FriendlyCreatureClass target=player.followers.get(followerNumInt);
Double attacknumD=mEntity.attacks.size()*Math.random();
Integer attacknum= attacknumD.intValue();
int enemydamage=mEntity.attacks.get(attacknum).getDamage();
target.health=target.health-enemydamage;
if(!target.isAlive()){
ioHandler.printToConsole("\nThe " + mEntity.name + " attacked " + target.name + " with " + mEntity.attacks.get(attacknum).getAttack() + " and did " + mEntity.attacks.get(attacknum).getDamage() + " damage! " + target.name+" died! Farewell "+target.name+".");
target.died(ioHandler, this, player, true);
//>>>> THIS IS WHERE I WOUlD LIKE TO REMOVE 'target' FROM THE env LIST <<<<
} else {
ioHandler.printToConsole("\nThe "+mEntity.name+" attacked "+target.name+" with "+mEntity.attacks.get(attacknum).getAttack()+" and did "+mEntity.attacks.get(attacknum).getDamage()+" damage! "+target.name+" has "+target.health+" health left!");
}
}
}
Please have mercy with my coding skills, since I am only a beginner in java / Android, though any suggestions are greatly appreciated!
Thanks in advance!
target) that is different from theIterator's current element (worldElement). This is quite an unusual situation. How do these elements relate to each other in the list? E.g. istargetalways to the left ofworldElement?