Search code examples
javastackloopsidentifier

How to get a object with a special id out of the stack?


In my cardgame-project, I simulate a cardpile with a stack. Each card of the pile/stack has an unique identifier.

Now I want to take the object with the specific identifier out of the stack. Is there an efficient option to realize it? First I thought about an iterator which will iterate over the stack... but it's not an optimum solution if I have many cards on the stack.


Solution

  • You might also keep a Map<Key, Card> to keep track of cards by their unique ID (Key might be String, Integer, etc). Then you could call remove(Object), which Stack inherits from Vector, passing in the Card you wanted removed.

    This is assuming you're constrained to the Stack data structure, which you may not be (see other answers).