Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign variable in a List within for-loop

Tags:

java

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?

like image 381
Đinh Carabus Avatar asked Jul 27 '13 10:07

Đinh Carabus


3 Answers

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.

like image 200
Sergey Kalinichenko Avatar answered Nov 10 '22 04:11

Sergey Kalinichenko


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.

like image 34
rocketboy Avatar answered Nov 10 '22 05:11

rocketboy


This code : enemy = new ExplodingEnemy(enemy.x, enemy.y); just creates a new enemy object. The old enemy object remains as it is.

like image 1
fastcodejava Avatar answered Nov 10 '22 03:11

fastcodejava