Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading