Dennis Grinch Dennis Grinch - 4 months ago 8
Java Question

Making array immutable

I am creating poker simulator for learning purposes, but having problem making

Deck
class immutable.

public class Deck {

private final Card[] cards;
private int cardCount;

public Deck(@NotNull Card[] c) {
this.cards = Arrays.copyOf(c, c.length);
this.cardCount = c.length - 1;
}

public Deck shuffle() {
// shuffle logic
return new Deck(this.cards);
}

public Card pop() {
return this.cards[cardCount--];
}
// other methods
}


Dealer
class holds
Deck
reference and implements dealing logic.

public class Dealer {

private final Deck deck;

public Dealer(@NotNull Deck d) {
this.deck = d;
}

public void deal(@NotNull Holder<Card> h) {
h.hold(deck.pop());
}
// other methods
}


As you can see
Deck
is not totally immutable, because it holds
cardCount
which is being updated every time when
pop
is called. !Note -
cardCount
is not visible to outside, also
Card
class is immutable.

Question 1: How this design affects
Deck
immutability?

Question 2: What could be future implications?

Question 3: Is it worth making
Deck
class totally immutable? If yes, then how?

Thank you for help.

Answer

This is one of the few cases where immutability doesn't help. You seem to need a mutable shared state, as this is the whole purpose of that Deck.

To make it immutable would mean that you'd have to create a new Deck with the remaining cards every time someone pops one out. But you have no control over the old Deck (before the top card removal), so this may still be referenced by some client -- which defeats the whole purpose of the game, in my opinion.

With your current implementation, you can run into problems with multiple threads so consider making your class thread safe. Using a java.util.Stack instead of an array with a counter would be a good first attempt.