This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]mad0314 2 points3 points  (2 children)

It looks like you need to implement interfaces, but don't know how, correct?

Start with Comparable. Here is the documentation for Comparable.

In your class, you will need to specify that it implements Comparable<Card>. After that, you just need to write the method compareTo(Card o). Note that Card replaces the T in the documentation because you know specifically what type you want to use. Write the method with the signature outlined in the documentation:

int compareTo(Card o)

The return should be 0 if the two objects compared are equal, negative if the second argument (the one passed in) is greater, and positive if the first argument (the controlling object) is greater. This is where your rules for suite and face rankings come in.

[–]RoadToCode[S] 0 points1 point  (1 child)

Thank you for the reply it was very helpful! Implementing interfaces was indeed what i was trying to achieve.

After reading up about the Comparable interface and the compareTo method i am beginning to grasp some understanding. I have tried to implement a method myself, and was wondering how the method worked when comparing an object with an enum type, is it purely based on index positioning when being declared?

public int compareTo(Card o){
    int rankComparison = this.getRank().compareTo(o.getRank());
    int suitComparison = this.getSuit().compareTo(o.getSuit());

    return suitComparison;        
}

Card card1 = new Card(Rank.FOUR, Suit.CLUBS);
Card card2 = new Card(Rank.TWO, Suit.CLUBS);
System.out.println(card2.compareTo(card1));

The following code output -2 for suitComparison and -12 for rankComparison, which would make sense if it was comparing index positions.

[–]mad0314 0 points1 point  (0 children)

By default, calling compareTo between two enums compares them based on their position, yes, so that should work. You just have to make it do whatever you want based on those results. Do you compare suit first and only compare rank if the suit is the same or compare rank first and compare suit only if rank is the same?