0

I have made this array of cards using enumerators for the suit and rank, but it is immutable. I cannot remove anything from the Deck. I can use shuffle by using

void shuffle() {
    List<Card> shuffold = Arrays.asList(cards);
}

I cannot use remove to deal cards even when using Arrays.asList(cards) I don't want to use a new deck every time I deal a card only when starting a new hand. Should I make the Deck an ArrayList or can I somehow convert it to a mutable set or is that even possible?

public class Deck {
    public final Card[] cards;
    public Deck() {
        cards = new Card[52];
        int i = 0;
        for (Suit suit : Suit.values()) {
            for (Rank rank : Rank.values()) {
                cards[i++] = new Card(rank, suit);
            }
        }
    }
}

I can already use shuffle but the array is still immutable in that I cannot use this to remove the first card in the deck:

void deal() {
    Collection deal = new ArrayList(Arrays.asList(cards));
    deal.remove(0);
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dogfac3
  • 13
  • 5
  • 1
    Does this answer your question? [How to convert an Array to a Set in Java](https://stackoverflow.com/questions/3064423/how-to-convert-an-array-to-a-set-in-java) – Tom Apr 20 '21 at 19:25

2 Answers2

3

You probably want a deck to be a List so it has an order, but that's easy enough. Just write

List<Card> shuffled = new ArrayList<>(Arrays.asList(cards));

or if you really want a set

Set<Card> shuffled = new HashSet<>(Arrays.asList(cards));
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

The main feature of the Arrays.asList method is that the returned list is backed by the specified array, so you can use the Collections methods on the array through this list. And since the array is of a fixed-size, this list is also of a fixed-size, but you can shuffle it or change it in some other way.

To specify the type of the returned collection, you can use the Java 8 toCollection method:

String[] arr = {"A", "B", "C"};

HashSet<String> set = Arrays.stream(arr)
        .collect(Collectors.toCollection(HashSet::new));

set.add("D");

System.out.println(set); // [A, B, C, D]