Q:

Reassign variable in a List within for-loop

I want to reassign a variable within a for loop traversing over an ArrayList of Objects. But whatever I try it seems that nothing has any effect. Basically my code looks like this: 
for (int i = 0; i < enemies.size(); i++) {
    AbstractEnemy enemy = enemies.get(i);

    if (enemy.intersects(bullet)) {
        enemy.getsHit(bullet.getDamage());
        bulletList.remove(bullet);
        if (enemy.isDead()) {

            // This does not work
            enemy = new ExplodingEnemy(enemy.x, enemy.y);

        }
    }
}

What am I doing wrong?

A:

Creating a new enemy does not have any effect because you are assigning the enemy object to a temporary variable with the lifetime limited to a single loop iteration. If you want to store the enemy object in the list of enemies, you need to add a call of set method, like this:
enemy = new ExplodingEnemy(enemy.x, enemy.y);
enemies.set(i, enemy);

this would replace the old object representing an enemy with the one you have just created.

A:

enemy = new ExplodingEnemy(enemy.x, enemy.y);

is just changing the reference and not the object referenced by the reference. For that you need an internal handle to the object in form of an exposed method, which can modify the object from inside.

