james james - 1 year ago 102
Java Question

Comparing rank in an enum

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'),

private char symbol;

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

public char getSymbol()
return this.symbol;

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()) {
} else {

Any ideas?

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download