Dennis Grinch Dennis Grinch - 1 year ago 67
Java Question

Making array immutable

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

class immutable.

public class Deck {

private final Card[] cards;
private int cardCount;

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

public Deck shuffle() {
// shuffle logic
return new Deck(;

public Card pop() {
// other methods

class holds
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) {
// other methods

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

Question 1: How this design affects

Question 2: What could be future implications?

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

Thank you for help.

Answer Source

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.