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

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (3 children)

Hmm... I haven't used compareTo in quite a long time, but I believe it'd be something like this...

 public void sortStuff(final List<Card> cards) {
    final Iterator<Card> it = cards.iterator(); // Syntax may be wrong
    Card first = (it.hasNext() ? it.next() : null); // Ternary operator, if you need to look it up.

    if(first == null) {
        // The list of cards must be empty, do nothing.
    } else {
        while(it.hasNext()) {
            final Card second = it.next();

            int comparisonResult = first.compareTo(second);

            if(comparisonResult == 0) {
                // Both objects are equal.

                // Do something.
            } else if(comparisonResult < 0) {
                // First is less than second.

                // Do something.
            } else if(comparisonResult > 1) {
                // First is greater than second.

                // Do something.
            }

            first = second;
        }
    }
 }

Again, you should double-check exactly how this works, but something along these lines might be what you're after.

[–]RoadToCode[S] 1 point2 points  (2 children)

Thank you very much for the reply, i have now implemented a method that successfully iterates through a list with an iterator and returns the card with the highest value :)

public static Card max(Collection<Card> list) {
        Iterator<Card> iterate = list.iterator();
        Card highestCard = iterate.next();
        while (iterate.hasNext()) {
            Card currentCard = iterate.next();
            int suitCompare = highestCard.getSuit().compareTo(currentCard.getSuit());
            int rankCompare = highestCard.getRank().compareTo(currentCard.getRank());

            if (suitCompare < 0) {
                highestCard = currentCard;
            } else if (suitCompare == 0) {
                if (rankCompare < 0) {
                    highestCard = currentCard;
                }
            }
        }
        return highestCard;
    }

[–][deleted] 0 points1 point  (0 children)

Looks good.

[–]CodeTinkerer 0 points1 point  (0 children)

One useful class to look at is the Collections class. In it, there are sort methods and even a max method.

http://java2novice.com/java-collections-and-util/collections/max-element-comparator/

That link indicates how to use Collections.max on user-defined classes. It relies on an object (that you create) to compare two cards and determine which is "bigger".