Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing rank in an enum

Tags:

java

enums

I have the following enum which represents a CardRank

public enum CardRank
{
    DEUCE('2'), TREY('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'),
    EIGHT('8'), NINE('9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), 
    ACE('A');

    private char symbol;

    private CardRank(char symbol)
    {
        this.symbol = symbol;
    }

    public char getSymbol()
    {
        return this.symbol;
    }
}

The CardRank is represented in ascending order. I need to compare the ranks in order to know which rank is greater than the other. I can use > operator with the numerical values but not with the char values.

// this will print out TRUE for all numerical values compared 
// but FALSE for the chars
if (card.getRank().getSymbol() > anotherCard.getRank().getSymbol()) {
    System.out.println("true");
} else {
    System.out.println("false");
}

Any ideas?

like image 357
monica Avatar asked May 19 '12 17:05

monica


2 Answers

if (card.getRank().compareTo(anotherCard.getRank()) > 0)

is what you need.

You may alwo use the ordinal:

if (card.getRank().ordinal() > anotherCard.getRank().ordinal())

Enums have a natural ordering defined by their ordinal. And the ordinal of an enum is attributed based on its position in the declaration. So DEUCE has ordinal 0, TREY has ordinal 1, etc.

like image 177
JB Nizet Avatar answered Sep 19 '22 20:09

JB Nizet


Consider using a Comparator for this. It can be a public static inner class if you desire:

import java.util.Comparator;

public enum CardRank implements Comparable<CardRank> {
   DEUCE('2'), TREY('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE(
         '9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), ACE('A');

   private char symbol;
   private static CardRankComparator cardRankComparator = new CardRankComparator();

   private CardRank(char symbol) {
      this.symbol = symbol;
   }

   public char getSymbol() {
      return this.symbol;
   }

   public int compareRank(CardRank otherCardRank) {
      return cardRankComparator.compare(this, otherCardRank);
   }

   // public so that this can be used for sorting if need be
   public static class CardRankComparator implements Comparator<CardRank> {
      private static final String RANKS = "23456789TJQKA";

      @Override
      public int compare(CardRank cr1, CardRank cr2) {
         int rank1 = RANKS.indexOf(String.valueOf(cr1.getSymbol()));
         int rank2 = RANKS.indexOf(String.valueOf(cr2.getSymbol()));
         return rank1 - rank2;
      }
   }
}
like image 23
Hovercraft Full Of Eels Avatar answered Sep 19 '22 20:09

Hovercraft Full Of Eels