Relating to my Poker Java program would it be a wise decision to choose enum's over chars and ints?
As far as I can tell assigning a separate integer value to a char has the benefit of ease of mathematical operators being applied when it comes to comparing card values to decide a winner. However this may be possible with enums, if so I'm unaware.
Please can someone explain the adv/disadv of each to me?
My first option of declaring card ranks is as enums:
public enum Rank {
DEUCE (1),
THREE (2),
FOUR (3),
FIVE (4),
SIX (5),
SEVEN (6),
EIGHT (7),
NINE (8),
TEN (9),
JACK (10),
QUEEN (11),
KING (12),
ACE (13)
}
public enum Suit {
CLUBS (1),
DIAMONDS (2),
HEARTS (3),
SPADES (4)
}
My second option is as static final chars with assigned int values as such:
public static final char ACE = 'A';
public static final char TWO = '2';
public static final char THREE = '3';
public static final char FOUR = '4';
public static final char FIVE = '5';
public static final char SIX = '6';
public static final char SEVEN = '7';
public static final char EIGHT = '8';
public static final char NINE = '9';
public static final char TEN = 'T';
public static final char JACK = 'J';
public static final char QUEEN = 'Q';
public static final char KING = 'K';
public Rank (char c)
{
switch (c)
{
case TWO:
_val = 0;
break;
case THREE:
_val = 1;
break;
case FOUR:
_val = 2;
break;
case FIVE:
_val = 3;
break;
case SIX:
_val = 4;
break;
case SEVEN:
_val = 5;
break;
case EIGHT:
_val = 6;
break;
case NINE:
_val = 7;
break;
case 'T':
_val = 8;
break;
case 'J':
_val = 9;
break;
case 'Q':
_val = 10;
break;
case 'K':
_val = 11;
break;
case 'A':
_val = 12;
break;
default:
_val = -1;
}
}
Thanks!
I'd suggest you read Item 30: Use enums instead of int constants from Effective Java by Joshua Bloch. It explains the many advantages to using enums over int constants.
Use enums. Because of:
Consider this method:
I can call it with invalid input
There's no range checking built in with
char
. But with enums, it comes for free.As for your issue of ranking, with enums you can simply do this
The order you define the enum instances in is enough to convey ranking order.
I would prefer
Enum
. Code looks cleaner and IDEs may help you to avoid missing a case inswitch
statements.Enums have an ordinal number (0-based). So you can use that to rank them and you probably shouldn't duplicate that. e.g. KING.ordinal().
Also, as an aside, in poker suits don't have a rank - you have your suits in bridge rank order.