Search code examples
javaarraylistslick2dsingle-threaded

Remove object by itself in ArrayList


I am working with single thread game, in Main class i have ArrayList to contain Bullet objects for attacking zombies. Each of frame of game i do loop like:

ArrayList<Bullet> bulletList;
for (Bullet iBullet : bulletList) {
    iBullet.move();
    iBullet.attack(bulletList);
}

In Bullet class, i wrote

public void attack(ArrayList<Bullet> bulletList) {
    for (Zombies z : zombieList) {
        if ( hit condition ) {
            bulletList.remove(this); //problem here
            return;
        }
    }
}

I got null error after first loop, seems bullet object had removed successfully from ArrayList and also made some confuses in loop of Main class.


Solution

  • You can use an Iterator, changing your attack method to accept it as a parameter:

    Iterator<Bullet> iterator = bulletList.iterator();
    while (iterator.hasNext()) {
        Bullet iBullet = iterator.next();
        iBullet.move();
        iBullet.attack(bulletList, iterator);
    }
    
    public void attack(ArrayList<Bullet> bulletList, Iterator<Bullet> iterator) {
        iterator.remove();
    }
    

    Or you can change your attack method to return a boolean indicating whether the bullet hit or not (instead of removing the bullet), and use the removeIf() method introduced in Java 8:

    for (Bullet iBullet : bulletList) {
        iBullet.move();
    }
    bulletList.removeIf(b -> b.attack());