Search code examples
javaiteratorcomparatorcloneable

Implementing a Deck of Cards in Java


So I have a lab (we are allowed to seek outside help on it, so here I am after lots of head scratching) where we have to implement a deck of cards. We have to use the enum class to create num

For Suits:

public enum Suits {
CLUBS, HEARTS, DIAMONDS, SPADES

}

For Numerals:

public enum Numerals {
DEUCE(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), 
TEN(10), JACK(11), QUEEN(12), KING(13), ACE(14);

}

My card class is pretty straightforward, but I'm not sure about these two blocks of code:

    public int compareTo (Card aCard){
    if (aCard.aNumeral.equals(this.aNumeral) && aCard.aSuit.equals(this.aSuit)){
        return 0;
    }
    else {
        return -1;
    }
}

and

    public boolean equals (Card aCard){
    if (this.compareTo(aCard) == 0){
        return true;
    }
    else {
        return false;
    }
}

Now for the tricky part...the Deck...

So we have to implement the deck using Cloneable, Iterable and Comparator, so here is what I have so far and just can't figure out what to.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;

public class Deck implements Cloneable, Iterable<Card>, Comparator<Card> {

private ArrayList<Card> cards;

public Deck (){
    for (Card c : cards){


    }

}

I'm struggling to even put together the constructor. I'm planning on using an ArrayList to essentially "hold" 52 sorted cards (as you can see); but we have to ultimately return a sorted deck. Any suggestions on where to go?


Solution

  • To answer the question about compareTo: a.compareTo(b) should return something negative if a is less than b, positive if a is greater than b, and 0 if they're equal. Also, if you're ordering the objects, one of the rules the ordering should follow is that if a.compareTo(b) < 0, then b.compareTo(a) > 0. (You can't have both "a is less than b" and "b is less than a"). Your compareTo, which just returns -1 anytime the cards aren't equal, doesn't follow this rule. To fix this, you'll need to decide on the ordering. What does a "sorted deck" look like? Probably all the clubs are together, followed by all the diamonds, etc., which means that any club card will be less than any diamond card. To do this correctly, you'll need to compare the suits first, and the ranks only if the suits are equal:

    public int compareTo (Card aCard){
        int suitCompare = this.aSuit.compareTo(aCard.aSuit);
        if (suitCompare != 0)  {
            return suitCompare;
        }
        return this.aNumeral.compareTo(aCard.aNumeral);
    }
    

    The compareTo on each enum will return <0, 0, or >0. So you can compare the suits, return a value that is <0 or >0, and then compare the ranks if the suits are equal. This is the general approach for writing any compareTo method where multiple pieces of data need to be checked.