Home > Mobile >  Is there a way to remove the first occurence of a specific object type from a linked list in Java?
Is there a way to remove the first occurence of a specific object type from a linked list in Java?

Time:11-28

I have a linked list of "gameObjects" called objects which contains instances of 2 subclasses, Beat, and Player. I want to remove the first instance of a beat in my linked list when a method is called. As it is the method removes a beat from a seperate linked list exclusively for beats, but since the beats are rendered using the second linked list, they do not disappear.

public static void hit(){
    //Method for player to hit the beat
    Beat currentObject = (Beat) Game.beatLinkedList.getFirst();
    int distanceToPlayer = currentObject.getX() - 200;
    if (distanceToPlayer <= 50){
        score  =100;
    }

    Game.beatLinkedList.removeFirst();
    System.out.println("Beat Linked List Length: "   Game.beatLinkedList.size());
    System.out.println("Score: "   score);
}

I've attempted to use removeFirstOccurence, but may have misinterpreted the meaning of this, and I know for sure the syntax is incorrect.

 Handler.object.removeFirstOccurrence(Beat.beat);

If anything else is needed for the question I'll add it when needed, but I think pretty much everything is there, sorry if not.

CodePudding user response:

You can use the instanceof keyword to check, for example the folowing code:

import java.io.IOException;
import java.util.ArrayList;


class GameObject {
    String name;

    public GameObject(String name) {
        this.name = name;
    }
}

class Player extends GameObject {

    public Player(String name) {
        super(name);
    }
}

class Entity extends GameObject {

    public Entity(String name) {
        super(name);
    }
}

public class Main {

    public static void main(String[] args) throws IOException {
        ArrayList<GameObject> list = new ArrayList<>();
        Player john = new Player("John");
        Entity doe = new Entity("Doe");
        Player jane = new Player("Jane");
        list.add(john);
        list.add(doe);
        list.add(jane);
        for (GameObject obj : list) {
            if (obj instanceof Player) {
                list.remove(obj);
                break;
            }
        }
    }
}

Removes the first occurrence of a GameObject of type Player.

  • Related