-3

How can I remove a card from an array in poker? Everything I've seen so far uses the "remove" method, but I am working with arrays and am not allowed to use that.

Here is my code so far:

private String name;
private int wins;
private Card[] hand;
private int cardsInHand;

public Player(String newName){
        name = newName;
        wins = 0;
        hand = new Card[5]
        cardsInHand = 0;
    }

    public void removeCard(Card cardToRemove){

    }
Pierre
  • 145
  • 1
  • 15
  • You'll have to traverse the array until you find the element you're looking for (suppose it's at index `n`) then you have to move the element at `hand[n+1]` to `hand[n]`, then the one at `hand[n+2]` to `hand[n+1]` and so on, then put the last element at `null`. – Federico klez Culloca May 21 '21 at 15:04
  • Does this answer your question? [How do I remove objects from an array in Java?](https://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) (there are array-only answers further down) – Federico klez Culloca May 21 '21 at 15:05

1 Answers1

0

Locate

First, locate the desired Card object in the array. To do so, your Card class must override the equals method (and hashCode) inherited from Object.

Or, in Java 16+, define your card class as a record. The compiler implicitly creates an override of equals (and hashCode) that examines each and every of the member fields.

Locate an existing Card object match by looping the array. Test each Card object in the array for equality with the target Card object passed as an argument.

Remove

Assigning null to a slot in your array clears any existing reference that may be stored there.

I expect that if you review your schoolwork notes and readings, you’ll find discussions about null.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154